如何避免大浮点或双精度值的四舍五入? [英] How to avoid rounding off of large float or double values?
问题描述
我正在处理一些c ++问题,应输出22258199.5000000这个数字,我已经存储的结果在双数据类型,当我试图打印该变量使用std :: cout它舍入到22258200.0000000,我不知道为什么这是什么?可以有人解释吗?我能做些什么来避免这个问题?
I am working on some c++ problem which should output 22258199.5000000 this number, I have stored the result in double datatype and when I tried to print that variable using std::cout it rounds off to 22258200.0000000, I don't know why is this happening? can anybody explain? what can I do to avoid this problem?
推荐答案
32位 float
类型大约有7个十进制数字,
A 32-bit float
type holds approximately 7 decimal digits, and anything beyond that will be rounded to the nearest representable value.
64位 double
类型约有15个
A 64-bit double
type holds approximately 15 decimal digits and also rounds values beyond that.
由于您的值四舍五入到最接近的7位数字,看起来您使用的是 float
变量。将 float
值复制到 double
将无法恢复丢失的数字。
Since your value is rounding to the nearest 7-digit number, it appears you're using a float
variable somewhere. Copying a float
value to double
doesn't restore the lost digits.
这不适用于你的例子,但在其他情况下 - 舍入以二进制,而不是十进制,所以你可能会得到一个值,似乎包含比我上面指出的更多的数字。只要知道只有前7或15将是十进制的准确。
This doesn't apply to your example, but it might in others - the rounding occurs in binary, not decimal, so you might end up with a value that appears to contain many more digits than I indicated above. Just know that only the first 7 or 15 are going to be accurate in decimal.
这篇关于如何避免大浮点或双精度值的四舍五入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!