在 Arduino 中除以两个整数

Divide two integers in Arduino

本文关键字:两个 整数 Arduino      更新时间:2023-10-16

我正在尝试将两个整数值相除并存储为浮点数。

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);
}

由于某种原因,我希望这是相当明显的,我似乎无法存储和显示正确的值。"test"变量始终设置为 0。

如何转换整数值?

它必须是您的LCD打印例程,因此您使用的铸件是正确的。

我在Arduino上使用串行打印而不是LCD进行了尝试。对于以下完整代码示例,预期结果显示在串行监视器(由菜单"工具"->"串行监视器"启动)中:

Start...
5
15
0.33
0.33333334922790

最后一个结果行确认它是一个 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()
{
}

>lcd.print不知道如何打印float,所以你最终打印的是整数。