有人可以解释我为什么在C++中发生这样的事情:如果我有为什么trunc(1)输出为0?
double tmp;
... // I do some operations with tmp
// after which it has to be equal to one
cout << tmp; // prints 1
cout << trunc(tmp); // prints 0
cout << trunc(tmp*10); // prints 9
我用这对小数部分例如从数量的分离部分权:5.010 ...我想有0.010 ..所以我使用:
double remainder = tmp - trunc(tmp);
我张贴整个代码....与地板的建议不工作
short getPrecision(double num, short maxPrecision) {
// Retrieve only part right of decimal point
double tmp = fabs(num - trunc(num));
double remainder = tmp;
// Count number of decimal places
int c = 0;
while (remainder > 0 && c < maxPrecision) {
tmp *= 10;
remainder = tmp - trunc(tmp);
c++;
}
return c;
}
当运行该功能例如具有5.1 remanider是0而不是1
,你能否告诉我们的操作?因为正如阿门的答案指出的那样,有时双重行动并不准确。 – quasiverse 2012-08-08 09:21:58
尝试在输出值之前将精度设置为17。 '<<'四舍五入(默认为6位精度)。截断和舍入给出不同的结果并不令人惊讶。 – 2012-08-08 09:28:14
或者你可以尝试输出tmp - 1.它看起来像我tmp不一定是1。 – 2012-08-08 09:50:07