arduino中的数学计算

Math calculations in arduino

我写了一个代码来用arduino uno做一个基本的计算。但它 returns 我对 filledPercentage 的回答是错误的。它总是-1。这有什么问题?

//include the library code:
#include <LiquidCrystal.h>

// initialize the library by associating any needed LCD interface pin
// with the arduino pin number it is connected to
const int rs = 13, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
int lowLevelDistance =112;
int highLevelDistance = 47;

void setup() {
// set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  Serial.begin(9600);
}

void loop() {
// set the cursor to column 0, line 1
// (note: line 1 is the second row, since counting begins with 0):
  lcd.setCursor(0, 1);
  int currentLevel = 101;

  int filledLevel = (lowLevelDistance - currentLevel);
  int fullLevel = (lowLevelDistance - highLevelDistance);
  int filledPercentage = filledLevel / (fullLevel / 100);

  Serial.println(lowLevelDistance);
  Serial.println(highLevelDistance);
  Serial.println(currentLevel);
  Serial.println(filledLevel);
  Serial.println(fullLevel);
  Serial.println(filledPercentage);
  delay(1000);
}

你不应该使用整数作为除法,你的 fulllevel / 100 returns 0.65 但随后被转换为整数(将其截断为 0)。

除以 0 会引发错误 (-1)。