C语言 用整数除以双精度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3051135/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 05:40:24  来源:igfitidea点击:

Dividing a double with integer

cfloating-pointprecisionfloating-accuracy

提问by hardcoder

I am facing an issue while dividing a doublewith an int. Code snippet is :

我在将 adoubleint. 代码片段是:

  double db = 10;
  int fac = 100;
  double res = db / fac;

The value of res is 0.10000000000000001instead of 0.10.

res 的值是0.10000000000000001代替0.10

Does anyone know what is the reason for this? I am using cc to compile the code.

有谁知道这是什么原因?我正在使用 cc 来编译代码。

回答by Rotsor

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.

CPU 使用数字的二进制表示。您的结果不能完全以二进制表示。二进制的 0.1 是 0.00011001100110011... CPU 在某个点截断它并得到一些舍入错误。

回答by Meiscooldude

double is a floating point operator, they do not provide precise values. Look up Precision and Floating Point Operators on google.

double 是浮点运算符,它们不提供精确值。在谷歌上查找精度和浮点运算符。