int类型的无效操作数和二进制'operator%'的double

Ras*_*yak 23 c++

编译程序后,我遇到错误

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

为什么会这样?

#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;
}
Run Code Online (Sandbox Code Playgroud)

Luc*_*ore 44

因为%只为整数类型定义.那是模数运算符.

5.6.2标准:

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

正如奥利指出的那样,你可以使用fmod().别忘了包括math.h.

  • 用法:包括“ math.h”,然后使用“ fmod(15,2);`”。在[`fmod` docs](http://www.cplusplus.com/reference/cmath/fmod/)中有更多信息。 (3认同)

Oli*_*rth 19

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