gpt4 book ai didi

c - 简化多个 elseif 语句

转载 作者:太空宇宙 更新时间:2023-11-04 05:33:19 24 4
gpt4 key购买 nike

我目前正在开发一个项目,该项目使用键盘数字作为传感器 (f_temp) 的保存位置并将其保存到 float 组 sensorData[] 中,u8_key 是识别按键的变量。我如何在不使用多个 else if 语句的情况下改进这一点?

void saveValue(void){
if (u8_key == '1'){
writeLCD(0x01,0,0,1); // clears LCD
sensorData[0] = f_temp;
outStringLCD("Saved to 1"); // writes to LCD for visual confirmation of value being saved and to what location on LCD
}

else if (u8_key == '2'){
writeLCD(0x01,0,0,1);
sensorData[1] = f_temp;
outStringLCD("Saved to 2");
}

else if (u8_key == '3'){
writeLCD(0x01,0,0,1);
sensorData[2] = f_temp;
outStringLCD("Saved to 3");
}
else if (u8_key == '4'){
writeLCD(0x01,0,0,1);
sensorData[3] = f_temp;
outStringLCD("Saved to 4");
}
else if (u8_key == '5'){
writeLCD(0x01,0,0,1);
sensorData[4] = f_temp;
outStringLCD("Saved to 5");
}
else if (u8_key == '6'){
writeLCD(0x01,0,0,1);
sensorData[5] = f_temp;
outStringLCD("Saved to 6");
}
else if (u8_key == '7'){
writeLCD(0x01,0,0,1);
sensorData[6] = f_temp;
outStringLCD("Saved to 7");

}
else if (u8_key == '8'){
writeLCD(0x01,0,0,1);
sensorData[7] = f_temp;
outStringLCD("Saved to 8");

}
else if (u8_key == '9'){
writeLCD(0x01,0,0,1);
sensorData[8] = f_temp;
outStringLCD("Saved to 9");

}
else if (u8_key == '0'){
writeLCD(0x01,0,0,1);
sensorData[9] = f_temp;
outStringLCD("Saved to 0");

}
else if (u8_key == '*'){
writeLCD(0x01,0,0,1);
sensorData[10] = f_temp;
outStringLCD("Saved to *");
}

最佳答案

最简单的解决方法是使用 switch...case 语句,例如

switch(u8_key)
{
case '1':
writeLCD(0x01,0,0,1); // clears LCD
sensorData[0] = f_temp;
outStringLCD("Saved to 1");
break;

case '2':
writeLCD(0x01,0,0,1); // clears LCD
sensorData[1] = f_temp;
outStringLCD("Saved to 2");
break;
...

等等。请注意,您需要 break 语句来确保一次只命中一个 case。

编辑:请注意,Christian Gibbons 的解决方案更高效、更优雅,您应该使用它。仅当您需要对每种情况执行不同的操作时才应使用 switch 语句。

关于c - 简化多个 elseif 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51678662/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com