C ++浮点数和精度 [英] C++ Float Division and Precision
问题描述
我知道511除以512实际上等于0.998046875。我也知道浮点的精度是7位数。我的问题是,当我做这个数学在C + +(GCC),我得到的结果是0.998047,这是一个舍入的值。我希望只是得到截断值0.998046,我该怎么办?
I know that 511 divided by 512 actually equals 0.998046875. I also know that the precision of floats is 7 digits. My question is, when I do this math in C++ (GCC) the result I get is 0.998047, which is a rounded value. I'd prefer to just get the truncated value of 0.998046, how can I do that?
float a = 511.0f;
float b = 512.0f;
float c = a / b;
推荐答案
作为 float
的 511/512
的值是精确的。不进行舍入。您可以通过要求超过七位数字来检查:
Well, here's one problem. The value of 511/512
, as a float
, is exact. No rounding is done. You can check this by asking for more than seven digits:
#include <stdio.h>
int main(int argc, char *argv[])
{
float x = 511.0f, y = 512.0f;
printf("%.15f\n", x/y);
return 0;
}
输出:
0.998046875000000
A code>不是作为十进制数存储,而是二进制。如果你用一个数字除以2的幂,例如512,结果几乎总是准确的。发生的是
float
的精度不是7位数,而是精确的23位。
A float
is stored not as a decimal number, but binary. If you divide a number by a power of 2, such as 512, the result will almost always be exact. What's going on is the precision of a float
is not simply 7 digits, it is really 23 bits of precision.
这篇关于C ++浮点数和精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!