双精度数除以整数
我在将 double
与 int
相除时遇到问题。代码片段为:
double db = 10;
int fac = 100;
double res = db / fac;
res 的值为 0.10000000000000001
而不是 0.10
。
有谁知道这是什么原因?我正在使用 cc 来编译代码。
I am facing an issue while dividing a double
with an int
. Code snippet is :
double db = 10;
int fac = 100;
double res = db / fac;
The value of res is 0.10000000000000001
instead of 0.10
.
Does anyone know what is the reason for this? I am using cc to compile the code.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
double 是浮点运算符,它们不提供精确值。在谷歌上查找精度和浮点运算符。
double is a floating point operator, they do not provide precise values. Look up Precision and Floating Point Operators on google.
CPU 使用二进制表示数字。
您的结果无法用二进制精确表示。
0.1 二进制为 0.00011001100110011...
CPU 在某个点截断它并产生一些舍入误差。
The CPU uses binary representation of numbers.
Your result cannot be represented exactly in binary.
0.1 in binary is 0.00011001100110011...
CPU truncates it at a certain point and gets some rounding error.
您需要阅读经典论文 What Every Computer Scientist Should Know About浮点运算。
You need to read the classic paper What Every Computer Scientist Should Know About Floating-Point Arithmetic.