有关功能的C 代码中的错误

  • 本文关键字:错误 代码 功能 c++
  • 更新时间 :
  • 英文 :


有人可以解释为什么我会遇到以下代码的错误(我已经附加了代码和错误,只需向下滚动)即可。实际上,这是一个家庭作业问题。我以前已经成功地在Python中完成了这个问题,所以现在我被要求在C 中做同样的问题,我基本上只是复制粘贴并更改了语法,但它并不能以某种方式工作。

代码

#include <iostream>
using namespace std;
float reduce(int num,float denom)
{
    float a;
    if (num>denom)
    {
        a = denom;
    }
    if (denom>num)
    {
        a = num;
    }
    float sol = 0;
    while (a>1)
    {
        if ( (num<=0) || (denom<=0) )
            a = -10;
        if ( (num%a == 0) && (denom%a == 0) )
        {
            sol = 1;
            a = -10;
        }
        a-=1;
    }
    return sol;
}
int main()
{
    float num;float denum;
    cout<<"Numerator: ";cin>>num;
    cout<<"Denominator: ";cin>>denum;
    float sol = Reduce(num,denom);
    cout<<sol;
}

错误

[Error] invalid operands of types 'int' and 'float' to binary 'operator%'
[Error] invalid operands of types 'float' and 'float' to binary 'operator%'

您无法一起获得浮点和int对象的mod。如果您需要整数mod,则

float a = 10.0;
int b = 10;
// parse float to int and get the mod
int mod = b % ((int)a); 

如果您想要绝对mod

float a = 10.5;
int b = 100;
int d = b / a;
float mod = b - (a * d);

根据建议编辑:
使用fmod功能。在<math.h>中定义FMOD参考

相关内容

最新更新