C语言 错误:取浮点模数时,二进制% 的操作数无效
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19317295/
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
error: invalid operands to binary % when taking modulus of float
提问by mjs
Its been a fairly long week, so forgive me if I am being thick.
这是一个相当长的一周,所以如果我很胖,请原谅我。
I have some code like:
我有一些代码,如:
float someFloat = 0;
//....do some stuff to someFloat
//....
if( someFloat % 1)
{
//take some action
}
I get a compiler error : error: invalid operands to binary %
我收到编译器错误: error: invalid operands to binary %
Assuming the compiler isnt on drugs, whats wrong with this?
假设编译器没有吸毒,这有什么问题?
EDIT: As an aside, what I actually wanted to do was detect non-integer value and round up. What I should have been doing was calling roundf (and I guess checking if the return is less than the operand and then incrementing if so, to take care that we have rounded up)
编辑:顺便说一句,我真正想做的是检测非整数值并四舍五入。我应该做的是调用 roundf (我想检查返回值是否小于操作数,如果是,则增加,以注意我们已经四舍五入)
回答by Paul R
%is an integer operator - use fmodor fmodffor doubles or floats.
%是整数运算符 - 将fmod或fmodf用于双精度或浮点数。
Alternatively if you expect your float to represent integer values then convert it to an intfirst, e.g.:
或者,如果您希望浮点数表示整数值,则将其转换为int第一个,例如:
if ((int)someFloat % 2 == 1) // if f is an odd integer value
{
...
}
回答by Jon
回答by Sohil Omer
%this only works with integers use fmod for floating point or double values**
%这仅适用于整数使用 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.

