【发布时间】:2015-03-12 06:52:06
【问题描述】:
我在玩下面这段代码
#include <iostream>
#include <cmath>
#include <cstdio>
using namespace std;
int main() {
double speed = 60.0;
double distance;
int a, b, c;
scanf("%lf %d %d %d", &distance, &a, &b, &c);
cout << distance << " " << a << " " << b << " " << c << endl;
cout << (fmod((distance*3600)/speed, (a + b + c))) << endl;
return 0;
}
并注意到,对于以下输入
15.1 1 1 1
它在我的机器上产生这个(不正确的?)结果
15.1 1 1 1
3
但它似乎在 ideone (http://ideone.com/mwMalv) 上产生了这个结果
15.1 1 1 1
0
我意识到“0.1”(在“15”中)不能准确地表示为双精度
http://www.exploringbinary.com/why-0-point-1-does-not-exist-in-floating-point/
但其他使用 gcc 4.8.2 运行此代码的人也可以获得在 ideone 上生成的内容。
我在VMware 6.0.5 build-2443746 和gcc version 4.8.2 (Ubuntu 4.8.2-19ubuntu1) 上运行Ubuntu 14.04.2 LTS Desktop (32-bit)。
什么给了?为什么fmod 在我的机器上的行为与在其他机器上的行为不同(假设编译器相同)?
【问题讨论】:
标签: c++ gcc g++ double modulus