0
How do i declare a variable that only returns the absolute of any value it receives?
3 Antworten
+ 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
+ 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;
+ 1
thanks guys. it worked!