C++ 表达式必须具有整数或非作用域枚举类型,位于 % 上。

huangapple go评论67阅读模式
英文:

C++ expression must have integral or unscoped enum type on %

问题

在这段代码中,我将余数定义为浮点数据类型,但编译器拒绝了,并建议将其定义为整数类型。这个问题的原因是什么?

int main()
{

    float days, hours, minutes, seconds;
    float Totalseconds;
    float Remainder;  // 这里的问题是余数Remainder的数据类型

    // 其余代码不变
}

问题出在代码中的Remainder变量的数据类型被定义为浮点型(float),但实际上在计算中,余数应该是整数类型,因为你想要得到秒数的整数部分。所以编译器建议将Remainder的数据类型更改为整数类型(比如int)以解决这个问题。

英文:

In this code I have defined the remainder in this code as float data type but the compiler rejected that and suppose to defien it as an inegral type what is the reasone for this issue?
enter image description here

int main()
{

    float days, hours, minutes, seconds;
    float Totalseconds;
    float Remainder;
    float secondsperday;
    float secondsperhour;
    float secondsperminute;

    secondsperday = 24 * 60 * 60;
    secondsperhour = 60 * 60;
    secondsperminute = 60;


    cout << "Enter total seconds\n";
    cin >> Totalseconds;

    days = floor(Totalseconds / secondsperday);
    Remainder = (Totalseconds % secondsperday);

    hours = floor(Remainder / secondsperhour);
    Remainder = Remainder % secondsperhour;

    minutes = floor(Remainder / secondsperminute);
    Remainder = Remainder % secondsperminute;

    seconds = Remainder;

    cout << days << ":" << hours << ":" << minutes << ":" << seconds;


    return 0;
}

答案1

得分: 1

> expression must have integral or unscoped enum type on %

在C++中,浮点数(如float)没有%运算符。它们既不是整数(例如int)也不是非作用域的枚举(即enum),因此您会收到此错误。

如果您想要一个类似于%运算符的浮点数余数,您可以使用std::fmod函数:

Remainder = std::fmod(Totalseconds, secondsperday);

但是,在您的代码中,似乎没有必要将所有数字都更改为float(除非Totalseconds可以是例如123.456)。
如果您只是将所有float类型更改为int,此代码也将编译通过。

英文:

> expression must have integral or unscoped enum type on %

Floating-point numbers like float don't have a % operator in C++.
They are neither integral (i.e. integers like int) nor unscoped enumerations (i.e. enum), so you're getting this error.

If you wanted a floating-point remainder that works similarly to % operator, you could use std::fmod:

Remainder = std::fmod(Totalseconds, secondsperday);

However, in your code, it looks like none of the numbers have to be float (unless Totalseconds can be 123.456 for example).
If you simply changed all of the float types to int, this code would also compile.

huangapple
  • 本文由 发表于 2023年6月26日 08:10:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/76552878.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定