abs()
Description
Calculates the absolute value of a number.
Syntax
abs(x)
Parameter Values
- x: the number
Return Values
- x: if x is greater than or equal to 0.
- -x: if x is less than 0.
Example Code
void setup() {
Serial.begin(9600);
int x = -4;
int y = abs(x);
Serial.print("The absolute value of of ");
Serial.print(x);
Serial.print(" is ");
Serial.println(y);
}
void loop() {}
The result in Serial Monitor:
COM6
The absolute value of of -4 is 4
Autoscroll
Clear output
9600 baud
Newline
※ NOTES AND WARNINGS:
Because of the way the abs() function is implemented, avoid using other functions inside the brackets, it may lead to incorrect results.
abs(a++); // avoid this - yields incorrect results
// use this instead:
abs(a);
a++; // keep other math outside the function
See Also
※ ARDUINO BUY RECOMMENDATION
Arduino UNO R3 | |
Arduino Starter Kit |
Disclosure: Some links in this section are Amazon affiliate links. If you make a purchase through these links, we may earn a commission at no extra cost to you.
Additionally, some links direct to products from our own brand, DIYables.
Additionally, some links direct to products from our own brand, DIYables.