0

How do i declare a variable that only returns the absolute of any value it receives?

19th Jan 2017, 6:01 PM
Cody Arthur
Cody Arthur - avatar
3 odpowiedzi
+ 3
You could use the "unsigned int" data type this will only store positive values. Also you could use the absolute value function in the standard library and the 'cmath' library. This will take any integer value and make it positive. Example: #include<iostream> #include<cmath> using namespace std; int main() { int x; x = abs(-9); cout<< x ; return 0; } This will output 9 even though the input was -9. You could take your input and run it through this code or something similar. This code actually works btw
19th Jan 2017, 6:37 PM
Sean Kudebeh
Sean Kudebeh - avatar
+ 2
Variables don't return anything, but you could use a macro: #define abs(a) ((a) < 0 ? -(a) : (a)) Define this at the top of your program (like after your includes) and use it like a function. Example: int x; cin >> x; cout << abs(x) << endl;
19th Jan 2017, 6:21 PM
Robobrine
Robobrine - avatar
+ 1
thanks guys. it worked!
19th Jan 2017, 10:30 PM
Cody Arthur
Cody Arthur - avatar