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

标签 c++

编译程序后出现以下错误

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

为什么会这样?

#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;
}

最佳答案

因为 % 只为整数类型定义。这就是模运算符。

标准的5.6.2:

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

正如 Oli 指出的,您可以使用 fmod()。不要忘记包含 math.h

关于c++ - int 和 double 类型的无效操作数到二进制 'operator%',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9278224/

相关文章:

c++ - 我如何在 Qt 中选择构建选项

c++ - 使用 int() 进行变量初始化

c++ - 操作数的求值顺序

c++ - std::map、引用、指针和内存分配

c++ - 从命令行运行到 "Run without Debugging"的不同行为

c++ - 如何在 Qt 中合并两个 QJsonObjects?

c++ "no appropriate default constructor available"错误使用模板类数据成员

c++ - 使用 Ceres 优化多维函数

c++ - 在 C++ 中从目录中列出文件时出错

c++ - 派生类成员由基类构造函数初始化