[CPP]cpp小笔记2 --- float 的值的精度最大为Decimal point 往左6-7位

本文深入探讨了单精度浮点数(float)在计算机中的存储方式及运算原理,通过具体示例揭示了float类型在cpp中的存储机制、最大数值限制以及浮点运算过程中的精度损失问题。了解这些概念对于程序员在进行数值计算时避免潜在错误至关重要。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

2. float 的值的运算

c++ primier plus中有一段关于float运算的代码:

float a = 2.34E+22f;
float b = a + 1.0f;
cout << "a =" << a <<endl;
cout << "b -a =" << b - a<< endl;

结果是:

a =2.34e+22
b - a =0

这是为什么呢?

The single precision floating point type float is like this(assuming IEEE-754)

single precision floating point

cpp在保存float type时,使用单精度#single precision#来保存float.格式是

m*2^e
where m is a number between 223 and 224,and e is an integer. 从上图来看,m的最大值是  223 #最大16777215# and e的最大值是 28


float在保存是会被rounded到最接近这个float的数值。 So the value 2.34e+22 is actually rounded to 

10391687*251, which is 23399998850475413733376. This is the value of a.


再有,float的运算结果也会被rounded到最接近的float数值。 if you add 1 to a, the result is 

23399998850475413733377, which is again rounded to the nearest floating-point number, which is still, of course, 

23399998850475413733376. So b gets the same value as a. Since both numbers are equal, a - b == 0.



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值