Barry P Barry P - 1 year ago 53
C++ Question

Converting a negative value to a positive value using n < 0 ? -a : a

The problem is I don't know how to use this piece code

n < 0 ? -n : n
to turn a negative number to a positive number. I know there are a lot of methods to do this, but my professor requires me to use the method above to convert negative numbers. The problem I got is that my program does not convert to a positive number.

int a, result;
cin >> a;
result = a < 0 ? -a : a;
cout << result % 10 << endl;

Input: -1

Output: -1

enter image description here

Answer Source

If a < 0 is true the Code between '?' and ':' is executed. If it's false the code between ':' and ';'. You didnt assigned the value to a.

a < 0 ? a = -a : a = a; 

UPDATE: The Better Solution is:

a = a<0 ? -a : a;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download