// cmath's abs example
#include <iostream>
#include <cmath>
usingnamespace std;
int main ()
{
cout << "The absolute value of 3.1416 is " << abs (3.1416) << endl;
cout << "The absolute value of -10.6 is " << abs (-10.6) << endl;
return 0;
}
The output I receive is:
The absolute value of 3.1416 is 3
The absolute value of -10.6 is 10
Press any key to continue
This output is different from the output of the reference:
The absolute value of 3.1416 is 3.1416
The absolute value of -10.6 is 10.6
Could you explain me why this happens and how I could fix this?
In C - abs took an int parameter, and if you wanted to get the absolute value of
a floating point you use fabs.
These are the functions that VC6 is using - so your floating points are getting truncated to integer first.
In later microsoft compilers like VC2008 - abs has been added to the standard namespace (but not fabs) and there have been overloads added to abs for various types like float, double etc...
**Whether this was just a Microsoft specific update or a C++ standard update I really can't say**
Thank you for your reply, guestgulkan. I have been searching with Google a lot but I couldn't find some (good) references for the facts you mentioned.
Following your answer, I have another question: Is there anyway to force it not to behave like in C but C++ so that abs will return the right absolute value for float?
I personally think you should upgrade from VC 6 - it was a useful thing in it's day - but it has some known problems and it is not up to date on the C++ standards and so you will keep finding these anomalies with it.