a simple problem about printf("%f",f)

J

Jude

here is the source code:
#include<stdio.h>
int main()
{
float f;
scanf("%d%f",&f);
printf("The float is %10.5f\n",f);
return 0;
}
when I input 12345.11111,the output is 12345.11133.
what wrong with it?
I compile it with vc++6.0.
 
K

Keith Thompson

Jude said:
here is the source code:
#include<stdio.h>
int main()
{
float f;
scanf("%d%f",&f);
printf("The float is %10.5f\n",f);
return 0;
}
when I input 12345.11111,the output is 12345.11133.
what wrong with it?
I compile it with vc++6.0.

Is that really the source code you compiled? The format string for
scanf() expects a pointer to int ("%d") and a pointer to float ("%f"),
but you only give it a pointer to float.

Assuming you drop the "%d", the behavior you're seeing is
unsurprising. The value 12345.11111 cannot be represented exactly in
binary floating-point, and type float in particular is only guaranteed
to support 6 decimal digits (double supports at least 10). The
closest approximation in type float to 12345.11111 is probably
something like 12345.111328125.

See section 14 of the comp.lang.c FAQ, <http://www.c-faq.com/>.

For a more advanced treatment, see David Goldberg's paper "What Every
Computer Scientist Should Know About Floating-Point Arithmetic".
 
M

Martin Ambuhl

Jude said:
here is the source code:
#include<stdio.h>
int main()
{
float f;
scanf("%d%f",&f);
printf("The float is %10.5f\n",f);
return 0;
}
when I input 12345.11111,the output is 12345.11133.
what wrong with it?
I compile it with vc++6.0.
All floating point types have limits on their precision. Interpreting
digits beyond that is pointless. Run the following with your
implementation and see what happens:

#include <stdio.h>
#include <float.h>

int main()
{
float xf;
double xd;
long double xld;
char *src[] = { "12345.11111", "12345.11133" };
size_t i, n = sizeof src / sizeof *src;
for (i = 0; i < n; i++) {
printf("input string is \"%s\"\n", src);
sscanf(src, "%f", &xf);
printf("Read into a float: %.*g\n", FLT_DIG, xf);
sscanf(src, "%lf", &xd);
printf("Read into a double: %.*g\n", DBL_DIG, xd);
sscanf(src, "%Lf", &xld);
printf("Read into a long double: %.*Lg\n\n", LDBL_DIG, xld);
}
return 0;
}

input string is "12345.11111"
Read into a float: 12345.1
Read into a double: 12345.11111
Read into a long double: 12345.11111

input string is "12345.11133"
Read into a float: 12345.1
Read into a double: 12345.11133
Read into a long double: 12345.11133
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top