错误消息:二进制“ operator%”的类型为“ float”和“ int”的无效操作数

问题描述

环境::Arduino IDE(v1.8.13)

在我的一个项目中,我试图使用浮点数据类型显示十进制温度值(temp),此代码对于int数据类型正确运行。有谁能帮助我解决错误“类型为'float'和'int'的无效操作数为二进制'operator%'”。我是编程的初学者

作为参考,我对click hereclick here进行了故障排除

1Float Data Type in Switch Statement,但找不到特定的解决方案。

先谢谢您!

完整程序:

  switch (current_digit)
  {
   case 1:
    disp((temp / 100) % 10);
    digitalWrite(Dig1,LOW);  // turn on digit 1
  break;

case 2:
  disp( (temp / 10) % 10);   // prepare to display digit 2
  digitalWrite(SegDP,LOW);  // print decimal point ( . )
  digitalWrite(Dig2,LOW);   // turn on digit 2
  break;

case 3:
  disp(temp % 10);   // prepare to display digit 3
  digitalWrite(Dig3,LOW);    // turn on digit 3
}

current_digit = (current_digit % 3) + 1;
}

  }

解决方法

如上所述,%用于整数类型。

要获取您的值的第一个小数位并从您的值中减去该舍入后的数字。将差值相乘10。您可以通过使用下限函数或强制转换为整数来消除小数点。

简化示例:

12.5... -> 12
12.5... - 12 -> 0.5...
0.5... * 10 -> 5.00...
5.0... -> 5

或者将您的值转换为char数组。这将使您方便地访问每个数字。 更改显示功能,使它们将采用char值。