【问题标题】:invalid operands to binary expression ('double' and 'double') [duplicate]二进制表达式的无效操作数('double'和'double')[重复]
【发布时间】:2016-12-12 22:56:27
【问题描述】:

这不是我的全部代码,但我不断收到此错误:二进制表达式的操作数无效

printf("How much change is owed?\n");
float change= GetFloat();
float roundf(float change);
change*=100;
int rem;

while (change>0)

{
    if(change>=0.25)
    rem=change % 0.25;      > error, saying that this is a double???? 
}
printf ("%d\n", rem);          I need the modulo , it is not working
return 0;

【问题讨论】:

  • 使用 fmod(a, b) 代替。
  • 乘以 100 并四舍五入后,您应该能够使用整数数学和整数变量编写程序的其余部分。
  • 嗯,如果change > 0.0 那么while (change>0) { if(change>=0.25) rem=whatever; } 看起来像一个无限循环。
  • 如果您需要精确算术结果,请不要使用浮点数。

标签: c int double


【解决方案1】:

在 C 和 C++ 中,运算符 % 没有为浮点数定义。它仅针对整数类型定义。

所以编译器会发出错误,因为在这个表达式中

rem=change % 0.25;

两个操作数都是浮点数。这里0.25double 类型的浮动文字,变量change 被声明为具有float 类型。

float change= GetFloat();

使用来自<math.h>fmodremainder 函数。

【讨论】:

    猜你喜欢
    • 2012-09-24
    • 1970-01-01
    • 2018-10-25
    • 1970-01-01
    • 1970-01-01
    • 2019-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多