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

时间:2012-08-08 09:19:02

标签: 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

我使用这个用于分隔小数部分右边的数字,例如,如果我有: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;
}

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

2 个答案:

答案 0 :(得分:6)

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

答案 1 :(得分:1)

请参阅http://en.cppreference.com/w/cpp/numeric/math/trunc处的图片。那里的图表解释了与trunc 1的不一致。可能同样适用于10

这可以帮助您实现所需:

double remainder = tmp - floor(tmp);