英文:
how to check the range using only if statement
问题
代码:
System.out.println("输入右前压力:");
frontR = keyboard.nextInt();
if (frontR >= 32 && frontR <= 42) {
inflation = "正常";
}
else {
warning = "警告:压力超出范围";
inflation = "异常";
}
System.out.println("输入左前压力:");
frontL = keyboard.nextInt();
if (frontL >= 32 && frontL <= 42) {
inflation = "正常";
}
else {
warning = "警告:压力超出范围";
inflation = "异常";
}
英文:
How can I write the code with a specific requirement having the range between frontR
and frontL
that must be between 1-3
?
Code:
System.out.println("Input right front pressure: ");
frontR = keyboard.nextInt();
if (frontR >= 32 && frontR <= 42) {
inflation = "good";
}
else{
warning = "Warning: pressure is out of range";
inflation = "BAD";
}
System.out.println("Input left front pressure: ");
frontL = keyboard.nextInt();
if (frontL >= 32 && frontL <= 42) {
inflation = "good";
}
else {
warning = "Warning: pressure is out of range";
inflation = "BAD";
}
答案1
得分: 0
如果你想要比较两个数之间的差异,你需要将它们相减。如果第一个数小于第二个数,结果可能为负,所以你可能想要使用 `Math.abs()` 函数,它会使结果变为正数。然后你会得到一个正数,你可以检查它是否介于1和3之间:
int difference = Math.abs(frontL - frontR);
if (difference >= 1 && difference <= 3) {
inflation = "good";
}
else {
warning = "警告:检测到左右压力差异";
inflation = "不好";
}
英文:
if you want to check the difference between two numbers, you need to subtract them. The result may be negative if the first number is smaller than the second, so you may want to use Math.abs()
which will make it positive again. Then you have a positive number that you can check for being between 1 and 3:
int difference = Math.abs(frontL - frontR);
if (difference >= 1 && difference <= 3) {
inflation = "good";
}
else {
warning = "Warning: difference between pressure left and right detected";
inflation = "BAD";
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论