为什么增加了两个浮点数的是在C不正确的? [英] Why does the addition of two float numbers is incorrect in C?

查看:91
本文介绍了为什么增加了两个浮点数的是在C不正确的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有增加两个浮点数的一个问题。
低于code:

I have a problem with the addition of two float numbers. Code below:

float a = 30000.0f;
float b = 4499722832.0f;

printf("%f\n", a+b);

为什么输出结果是450002816.000000? (正确的应该是450002832。)

Why the output result is 450002816.000000? (The correct one should be 450002832.)

推荐答案

浮动不会再$ P $用C究竟psented - 看的http://en.wikipedia.org/wiki/Floating_point#IEEE_754:_floating_point_in_modern_computers http://en.wikipedia.org/wiki/Single_$p$pcision,所以用浮动计算只能给出一个近似的结果。

Float are not represented exactly in C - see http://en.wikipedia.org/wiki/Floating_point#IEEE_754:_floating_point_in_modern_computers and http://en.wikipedia.org/wiki/Single_precision, so calculations with float can only give an approximate result.

这是对于较大的值尤其明显,因为可能差可以重新psented作为值的百分比$ P $。在增加/减少的两个值的情况下,你会得到双方的糟糕precision(和结果)。

This is especially apparent for larger values, since the possible difference can be represented as a percentage of the value. In case of adding/subtracting two values, you get the worse precision of both (and of the result).

这篇关于为什么增加了两个浮点数的是在C不正确的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆