4

这是一个相当长的一周,如果我很厚,请原谅我。

我有一些代码,例如:

float someFloat = 0;
//....do some stuff to someFloat
//....

if( someFloat % 1)
{
   //take some action
}

我得到一个编译器错误:error: invalid operands to binary %

假设编译器不吸毒,这有什么问题?

编辑:顺便说一句,我真正想做的是检测非整数值并四舍五入。我应该做的是调用roundf(我想检查返回是否小于操作数,如果是,则增加,以注意我们已经四舍五入)

4

3 回答 3

18

%是一个整数运算符 - 使用fmodfmodf表示双精度数或浮点数。

或者,如果您希望您的浮点数表示整数值,则将其转换为int第一个值,例如:

if ((int)someFloat % 2 == 1) // if f is an odd integer value
{
    ...
}
于 2013-10-11T11:42:09.463 回答
3

模运算符仅适用于整数。对于浮点值,请使用fmodor fmodf

于 2013-10-11T11:42:32.373 回答
2

%这仅适用于整数使用 fmod 浮点或双精度值**

double fmod(double x, double y)


x -- This is the floating point value with the division numerator i.e. x.

y -- This is the floating point value with the division denominator i.e. y.
于 2013-10-11T11:46:02.110 回答