C++ 错误中的舍入数字 - 表达式必须具有整数或枚举类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16969137/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 20:47:28  来源:igfitidea点击:

Rounding numbers in C++ error - expression must have integral or enum type

c++enums

提问by CJH

I have a function which is designed to round a number down to the nearest even number.

我有一个函数,旨在将数字四舍五入到最接近的偶数。

double round(double d)
{
  floor(d + 0.5);
  if(d % 2 == 1)
  {
      d = d-1;
  }
  return d;
}

However, this returns the error "expression must have integral or enum type" when I try to compile the code. The error is reported from the same line as the if statement.

但是,当我尝试编译代码时,这会返回错误“表达式必须具有整数或枚举类型”。该错误是从与 if 语句相同的行报告的。

Can anyone point me in the right direction?

任何人都可以指出我正确的方向吗?

回答by djf

The % operator is only defined for integers. You wanna use the fmod() function.

% 运算符仅针对整数定义。你想使用fmod() 函数

Bill is rightabout a proper implementation of round(double x).

Bill正确实现round(double x).

回答by Bill Carey

The floor()function returns a double:

floor()函数返回一个双精度:

double floor (double x);

which is a floating point type, not an 'integral type', like intor char. Instead of calling floor(d + 0.5);which rounds dand discards the result, you'd want something like:

这是浮点类型,而不是“整数类型”,例如intor char。您不需要调用floor(d + 0.5);which 舍入d并丢弃结果,而是需要以下内容:

int i = static_cast<int>(floor(d + 0.5));

回答by Joop Eggen

return floor(d/2 + 0.5) * 2;

Of course doubles are an approximation. For 10^50 you won't get even numbers probably.

当然,双打是一个近似值。对于 10^50,您可能不会得到偶数。

回答by naumcho

floor doesn't work in place, it returns the floor-ed value. Also % applies for integers so you can't re-use d. What you want is:

floor 不起作用,它返回 floor-ed 值。% 也适用于整数,因此您不能重复使用d. 你想要的是:

  int i = floor(d + 0.5);
  if(i % 2 == 1)
  {
      i = i-1;
  }
  return i;

回答by abelenky

This version will do what you ask, returning an int.

这个版本会按照你的要求做,返回一个int.

If the parameter dis outside the range of an int, it returns 0instead.
(maybe you want to throw an OutOfRangeexception or something)

如果参数d超出 an 的范围int,则返回0
(也许你想抛出OutOfRange异常什么的)

int roundDown2Even(double d)
{
    return (INT_MIN <= d && d <= INT_MAX)? ((int)d) & ~1 : 0;
}