【问题标题】:How to correct this arithmetic operation without the need to use fmod?如何在不需要使用 fmod 的情况下更正这个算术运算?
【发布时间】:2021-12-30 16:40:07
【问题描述】:

c++ 中,以下代码显示错误:

expression must have integral or unscoped enum type
illegal left operand has type 'double'

是否可以在不需要使用fmod的情况下更正它?

# include <iostream>    
using namespace std;

int main()
{
    int x = 5, y = 6, z = 4;
    float w = 3.5, c;
    c = (y + w - 0.5) % x * y;   // here is the error
        cout << "c = " << c << endl;

    return 0;
}

【问题讨论】:

  • 先切换到int
  • 您能评论一下您希望(y + w - 0.5) % x * y 做什么吗?
  • 我做了,编译器输出9,计算器显示24!
  • 您认为% 操作员是做什么的?

标签: c++ visual-studio


【解决方案1】:

您可以使用type casting 修复它:

c = ((int) (y + w - 0.5)) % x * y;

为了澄清您在 cmets 中的回复,将 c 更改为类型 int 仍然不起作用,因为部分 (y + w - 0.5) 未评估为 int 而是评估为 double。而modulus operation 不会将该类型作为参数。

完整修改代码:

#include <iostream>
using namespace std;

int main()
{
    int x = 5, y = 6, z = 4;
    float w = 3.5, c; //c could still stayed as float
    c = ((int) (y + w - 0.5)) % x * y; //swapped out here
    cout << "c = " << c << endl;
}

输出:c = 24.

在这里要清楚,这只是针对这种情况的临时修复,当您知道(y + w - 0.5) 将有一个明确的整数值时。如果值类似于0.51.447,则需要std::fmod

这是关于float/doubleint/long long 之间交互的表达式中的类型转换规则的帖子:Implicit type conversion rules in C++ operators

【讨论】:

  • @sweenish 必须解决这个问题,谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-04-08
  • 1970-01-01
  • 1970-01-01
  • 2010-11-12
  • 1970-01-01
  • 1970-01-01
  • 2011-03-27
相关资源
最近更新 更多