C++ int 和 double 类型的无效操作数转为二进制“operator%”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9278224/
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 12:35:45  来源:igfitidea点击:

invalid operands of types int and double to binary 'operator%'

c++

提问by Rasmi Ranjan Nayak

After compiling the program I am getting below error

编译程序后,我收到以下错误

invalid operands of types int and double to binary 'operator%' at line 
"newnum1 = two % (double)10.0;"

Why is it so?

为什么会这样?

#include<iostream>
#include<math>
using namespace std;
int main()
{
    int num;
    double two = 1;
    double newnum, newnum1;
    newnum = newnum1 = 0;
    for(num = 1; num <= 50; num++)
    {

        two = two * 2;
    }
    newnum1 = two % (double)10.0;
    newnum = newnum + newnum1;
    cout << two << "\n";
    return 0;
}

回答by Luchian Grigore

Because %is only defined for integer types. That's the modulus operator.

因为%仅针对整数类型定义。那就是模运算符。

5.6.2 of the standard:

5.6.2 标准:

The operands of * and / shall have arithmetic or enumeration type; the operands of % shall have integral or enumeration type. [...]

* 和 / 的操作数应为算术或枚举类型;% 的操作数应为整数或枚举类型。[...]

As Oli pointed out, you can use fmod(). Don't forget to include math.h.

正如奥利指出的那样,您可以使用fmod(). 不要忘记包含math.h.

回答by Oliver Charlesworth

Because %only works with integer types. Perhaps you want to use fmod().

因为%只适用于整数类型。也许您想使用fmod().

回答by Amar

Yes. % operator is not defined for double type. Same is true for bitwise operators like "&,^,|,~,<<,>>" as well.

是的。% 运算符没有为 double 类型定义。对于像 "&,^,|,~,<<,>>" 这样的按位运算符也是如此。