Click to See Complete Forum and Search --> : Why this error happen?
phoenixbr
July 17th, 2005, 12:43 AM
float a=127.2344,c;
int b;
b = abs(a); <====1
c = a - b; <====2
1 - Return 127
2 - Return 0.234375 and the correct is 0.2344 - ERROR.
Why this problem happen? I really need the correct value. óÒ
Tks very much ^^
humptydumpty
July 17th, 2005, 01:14 AM
float a=127.2344,c;
int b;
b = abs(a); <====1
c = a - b; <====2
1 - Return 127
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 answer
double a=127.2344,c;
int b;
b = abs(a);
cout<<b;
c = a - b;
cout<<endl;
cout<<c;
due to decleration of float you was getting some thing
because compiler will treat it as double
phoenixbr
July 17th, 2005, 01:53 AM
Tks very much ^^
humptydumpty
July 17th, 2005, 01:57 AM
Tks very much ^^
you welcome
exterminator
July 17th, 2005, 01:59 AM
Read this FAQ (http://www.codeguru.com/forum/showthread.php?t=323835). Hope this helps. :thumb:
pumpkindyy
July 17th, 2005, 03:04 AM
float a=127.2344,c;
int b;
b = abs(a); <====1
c = a - b; <====2
1 - Return 127
2 - Return 0.234375 and the correct is 0.2344 - ERROR.
Why this problem happen? I really need the correct value. óÒ
Tks very much ^^
There are two implicit type conversion occured;
and the complier will transform the type of expression to assigned object.
Good Luck!
SuperKoko
July 17th, 2005, 03:18 AM
float a=127.2344,c;
int b;
b = abs(a); <====1
c = a - b; <====2
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.
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.
RoboTact
July 17th, 2005, 06:12 AM
You can use floor and fabs functions - it wouldn't require conversions:double a=127.2344;
double c=fabs(a)-floor(fabs(a));
NMTop40
July 17th, 2005, 06:59 AM
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.
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.