我试图划分两个整数值并存储为浮点数.
void setup()
{
lcd.begin(16, 2);
int l1 = 5;
int l2 = 15;
float test = 0;
test = (float)l1 / (float)l2;
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(test);
}
Run Code Online (Sandbox Code Playgroud)
由于某种原因,我期望相当明显,我似乎无法存储和显示正确的值.'test'变量始终设置为0.
如何转换整数值?
它必须是您的LCD打印程序,因此您使用的模型是正确的.
我在Arduino上尝试使用串行打印而不是LCD.预期结果显示在串行监视器中(由菜单工具 - > 串行监视器启动),完整的代码示例如下:
Start...
5
15
0.33
0.33333334922790
Run Code Online (Sandbox Code Playgroud)
最后一行结果确认它是一个4字节的浮点数,有7-8位有效数字.
/********************************************************************************
* Test out for Stack Overflow question "Divide two integers in Arduino", *
* <http://stackoverflow.com/questions/13792302/divide-two-integers-in-arduino> *
* *
********************************************************************************/
// The setup routine runs once when you press reset:
void setup() {
// Initialize serial communication at 9600 bits per second:
Serial.begin(9600);
//The question part, modified for serial print instead of LCD.
{
int l1 = 5;
int l2 = 15;
float test = 0;
test = (float)l1 / (float)l2;
Serial.println("Start...");
Serial.println("");
Serial.println(l1);
Serial.println(l2);
Serial.println(test);
Serial.println(test, 14);
}
} //setup()
void loop()
{
}
Run Code Online (Sandbox Code Playgroud)