【发布时间】:2014-11-27 22:05:51
【问题描述】:
我已经阅读了这些:
他们解释“如何”。我想知道为什么这些语言会有所不同。在相同输入的情况下,我希望得到类似的结果。
test.js
#!/usr/bin/env node
var nine = 9.0;
var pointOhOhOne = 0.001;
var result = nine * pointOhOhOne;
console.log(result);
test.java
public class test {
public static void main(String[] argv) {
double nine = 9.0d;
double pointOhOhOne = 0.001d;
double result = nine * pointOhOhOne;
System.out.println(result);
}
}
test.c
#include "stdio.h"
int main() {
double nine = 9.0;
double pointOhOhOne = 0.001;
double result = nine * pointOhOhOne;
printf("%f", result);
}
test.rb
#!/usr/bin/env ruby
nine = 9.0
pointOhOhOne = 0.001
result = nine * pointOhOhOne
print result
test.py
#!/usr/bin/env python
nine = 9.0
pointOhOhOne = 0.001
result = nine * pointOhOhOne
print result
结果:
ruby 0.009000000000000001
python 0.009
node 0.009000000000000001
java 0.009000000000000001
c 0.009000
【问题讨论】:
-
也许不同的语言都做得到相同的答案,但它们显示它的方式不同。例如,您可以使用
decimal模块在 Python 中获得更高的打印精度。import decimal; print decimal.Decimal(9.0 * 0.001)给0.009000000000000001054711873393898713402450084686279296875。 -
由于您实际上并没有测试任何值是否 equal 特别是,您的问题真的是关于为什么 representations i> 有什么不同?
-
默认看起来像 C/C+ prints 6 significant digits.
-
@rgettman:这 6 个小数位在 C 中得到保证,在 C++ 中通过引用来保证。
-
这里的元评论:有没有人认为这里有floating-point 或floating-point-precision 标签比所有5 种语言都更有用?我正在努力思考是什么让它出现在搜索结果中。
标签: floating-point