环境: Arduino IDE (v1.8.13)
在我的一个项目中,我尝试使用浮点数据类型显示十进制温度值(温度),此代码适用于 int 数据类型。任何人都可以帮我解决这个错误“'float'和'int'类型的无效操作数到二进制'operator%'”。我是编程初学者
作为引用,我做了这个故障排除 click here和 click here
1 : Float 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。您可以通过使用 floor 函数或转换为整数来消除小数。
简化示例:
12.5... -> 12
12.5... - 12 -> 0.5...
0.5... * 10 -> 5.00...
5.0... -> 5
或者将您的值转换为 char 数组。这将允许您方便地访问每个数字。更改您的显示功能,以便它们采用 char 值。
关于c++ - 错误消息 : Invalid operands of types 'float' and 'int' to binary 'operator%' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64041814/