Why does the value of this float change from what

2019-01-26 11:25发布

Why is this C program giving the "wrong" output?

#include<stdio.h>

void main()
{
    float f = 12345.054321;

    printf("%f", f);

    getch();
}

Output:

12345.054688

But the output should be, 12345.054321.

I am using VC++ in VS2008.

5条回答
疯言疯语
2楼-- · 2019-01-26 11:31

Single-precision floating point values can only represent about eight to nine significant (decimal) digits. Beyond that point, you're seeing quantization error.

查看更多
手持菜刀,她持情操
3楼-- · 2019-01-26 11:32

It's giving the "wrong" answer simply because not all real values are representable by floats (or doubles, for that matter). What you'll get is an approximation based on the underlying encoding.

In order to represent every real value, even between 1.0x10-100 and 1.1x10-100 (a truly minuscule range), you still require an infinite number of bits.

Single-precision IEEE754 values have only 32 bits available (some of which are tasked to other things such as exponent and NaN/Inf representations) and cannot therefore give you infinite precision. They actually have 23 bits available giving precision of about 224 (there's an extra implicit bit) or just over 7 decimal digits (log10(224) is roughly 7.2).

I enclose the word "wrong" in quotes because it's not actually wrong. What's wrong is your understanding about how computers represent numbers (don't be offended though, you're not alone in this misapprehension).

Head on over to http://www.h-schmidt.net/FloatApplet/IEEE754.html and type your number into the "Decimal representation" box to see this in action.

If you want a more accurate number, use doubles instead of floats - these have double the number of bits available for representing values (assuming your C implementation is using IEEE754 single and double precision data types for float and double respectively).

If you want arbitrary precision, you'll need to use a "bignum" library like GMP although that's somewhat slower than native types so make sure you understand the trade-offs.

查看更多
迷人小祖宗
4楼-- · 2019-01-26 11:35

The decimal number 12345.054321 cannot be represented accurately as a float on your platform. The result that you are seeing is a decimal approximation to the closest number that can be represented as a float.

查看更多
太酷不给撩
5楼-- · 2019-01-26 11:38

It's all to do with precision. Your number cannot be stored accurately in a float.

查看更多
Melony?
6楼-- · 2019-01-26 11:46

floats are about convenience and speed, and use a binary representation - if you care about precision use a decimal type.

To understand the problem, read What Every Computer Scientist Should Know About Floating-Point Arithmetic: http://docs.sun.com/source/806-3568/ncg_goldberg.html

For a solution, see the Decimal Arithmetic FAQ: http://speleotrove.com/decimal/decifaq.html

查看更多
登录 后发表回答