Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

what happened to this output? 2

Status
Not open for further replies.

chopstick

Programmer
Apr 9, 2006
8
SG
#include<stdio.h>
int main(void)
{
float c;
printf(" pls key in your code:");
scanf("%f",&c);
printf("the output is %f or %e",c,c);
system("pause");
return 0;
}

after I have compiled the code above, I typed in 21.29, and what I get is "the output is 21.290001 or 2.129000e+001", why I got the different figure here? Any suggestion? thanks.
 
From "printf format specification fields":

f
double
Signed value having the form [ – ]dddd.dddd, where dddd is one or more decimal digits. The number of digits before the decimal point depends on the magnitude of the number, and the number of digits after the decimal point depends on the requested precision.


e
double
Signed value having the form [ – ]d.dddd e [sign]dd[d] where d is a single decimal digit, dddd is one or more decimal digits, dd[d] is two or three decimal digits depending on the output format and size of the exponent, and sign is + or –.
 
The number 21.29 is a decimal fraction 2129/100. It's impossible to represent this number exactly as a binary fraction (base 2 arithmetics). So 32-bit binary float is never equal to 2129/100 (see ytailed ...0001).

Moreover, you may get 2129.0/100.0 != 21.29 as user input or source constant! Don't compare floats and doubles with == operator (except of == 0;).

Remember: floating point numbers are not math real numbers.
Don't use float type in intensive math calculations (use double). But double 2129.0/100/0 is not exactly 21.29 too.

Try to read a good book about computational math (or see Knuth's Bible Art of...).
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top