为什么trunc(1)输出为0?

Mic*_*hal 3 c++ double decimal-point truncation

有人可以解释一下为什么在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
Run Code Online (Sandbox Code Playgroud)

我使用这个来分隔小数部分右边的数字,例如,如果我有:5.010 ...我想要0.010 ..所以我使用:

double remainder = tmp - trunc(tmp);
Run Code Online (Sandbox Code Playgroud)

我发布了整个代码....地板的建议没有用

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;
}
Run Code Online (Sandbox Code Playgroud)

当我以5.1运行此函数时,remanider为0而不是1

Arm*_*yan 6

经过一些计算,它必须是一个?好吧,它也可以0.99999999999999999.浮点运算不精确,您应该始终考虑到这一点.