Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
484 views
in Technique[技术] by (71.8m points)

c++ - Unexpected Output when adding two float numbers

I wrote the following C++ code:

float a, b;
int c;

a = 8.6;
b = 1.4;
c = a + b;

printf("%d
", c);

The output is 10.

But when I run the following code:

float a, b;
int c;

a = 8.7;
b = 1.3;
c = a + b;

printf("%d
", c);

The output is 9.

What is the difference between the two, as they are giving different outputs?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There is no such number as 8.7 or 1.3 in floating point. There is a number 10, and a number -6.5, and a number 0.96044921875... but no 8.7 or 1.3.

At best, your computer can round 8.7 to the nearest floating point number, and round 1.3 to the nearest floating point number as well. The computer adds these rounded numbers to each other, and then rounds the result.

Do not use floating point numbers for money.

#include <stdio.h>
int main(int argc, char *argv[])
{
    float a = 8.7, b = 1.3;
    printf("Looks like: %.1f + %.1f = %.1f
", a, b, a+b);
    printf("The truth: %.20f + %.20f = %.20f
", a, b, a+b);
    return 0;
}

On an x86 GCC/Linux computer, I get the result:

Looks like: 8.7 + 1.3 = 10.0
The truth: 8.69999980926513671875 + 1.29999995231628417969 = 9.99999976158142089844

On a PPC GCC/OS X computer, I get the result:

Looks like: 8.7 + 1.3 = 10.0
The truth: 8.69999980926513671875 + 1.29999995231628417969 = 10.00000000000000000000

Notice how 8.7 and 1.3 are both rounded down in this particular case. If you chose numbers that get rounded up, you might see a number larger than 10 on the right hand side.

See What Every Computer Scientist Should Know About Floating-Point Arithmetic, by David Goldberg (link).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...