1 - Return 127Code:float a=127.2344,c;
int b;
b = abs(a); <====1
c = a - b; <====2
2 - Return 0.234375 and the correct is 0.2344 - ERROR.
Why this problem happen? I really need the correct value. óÒ
Tks very much ^^
Printable View
1 - Return 127Code:float a=127.2344,c;
int b;
b = abs(a); <====1
c = a - b; <====2
2 - Return 0.234375 and the correct is 0.2344 - ERROR.
Why this problem happen? I really need the correct value. óÒ
Tks very much ^^
here is your answerQuote:
Originally Posted by phoenixbr
due to decleration of float you was getting some thingCode:double a=127.2344,c;
int b;
b = abs(a);
cout<<b;
c = a - b;
cout<<endl;
cout<<c;
because compiler will treat it as double
Tks very much ^^
you welcomeQuote:
Originally Posted by phoenixbr
Read this FAQ. Hope this helps. :thumb:
There are two implicit type conversion occured;Quote:
Originally Posted by phoenixbr
and the complier will transform the type of expression to assigned object.
Good Luck!
Quote:
Originally Posted by phoenixbr
- It converts from float to integer, then it computes the absolute value of the integer.
To avoid strange rounding rules, it may be preferable to use fabs which uses a double argument.
Code:b = fabs(a);
- It is a precision error, because 127.2344 cannot be correctly represented on a float number (float are binary numbers, not decimal numbers, so 1/5 for example cannot be correctly represented).
Using double values greatly increase the precision.
Note, that BC++ has a library for BCD (Binary coded decimals) floats, but use them only if you really need them, because it is not portable.
You can use floor and fabs functions - it wouldn't require conversions:Code:double a=127.2344;
double c=fabs(a)-floor(fabs(a));
You could also use boost::rational if you really want decimal fractions represented exactly.
An IEEE float gives 23 significant bits of data (22 bits but there is one assumed 1-bit) so that's about 8 million. Therefore you get just under 7 significant figures in decimal.