错误:C++ 中二进制"operator%"类型"float"和"int"的操作数无效

error: invalid operands of types 'float' and 'int' to binary 'operator%' in c++

本文关键字:int 无效 操作数 float operator% C++ 二进制 错误 类型      更新时间:2023-10-16

几周前刚开始在C++编程,我遇到了这个问题:

float a,i,b,c,d,e,f;
cin>>a;
cin>>c;
if(c%2==0)
{
    d=c;
    e=1;
}
else
{
    d=0;
    e=0;
}
for (i=2;i<=a;i++)
{
     cin>>b;
     if(b%2==0)
     {
         d=d+b;
         e=e+1;
     }
}
f=d/e;
if(e==0)
    cout<<"0";
else
    cout<<fixed<<setprecision(2)<<f;

理想情况下,程序应在屏幕上显示代表算术平均值的数字"f"。

% 运算符不是为实数定义的 - 您希望在 <cmath> 中声明 fmod() 函数。请参阅 http://en.cppreference.com/w/cpp/numeric/math/fmod