有人可以解释一下为什么在 c++ 中会发生这样的事情:
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