如何仅使用if语句来检查范围。

huangapple go评论70阅读模式
英文:

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(&quot;Input right front pressure: &quot;);
frontR = keyboard.nextInt();

if (frontR &gt;= 32 &amp;&amp; frontR &lt;= 42) {
	inflation = &quot;good&quot;;
}
else{
		warning = &quot;Warning: pressure is out of range&quot;;
		inflation = &quot;BAD&quot;;
}

System.out.println(&quot;Input left front pressure: &quot;);
frontL = keyboard.nextInt();

if (frontL &gt;= 32 &amp;&amp; frontL &lt;= 42) {
	inflation = &quot;good&quot;;
}
else {
	warning = &quot;Warning: pressure is out of range&quot;;
	inflation = &quot;BAD&quot;;
}

答案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 &gt;= 1 &amp;&amp; difference &lt;= 3) {
    inflation = &quot;good&quot;;
}
else {
    warning = &quot;Warning: difference between pressure left and right detected&quot;;
    inflation = &quot;BAD&quot;;
}

huangapple
  • 本文由 发表于 2020年8月28日 14:46:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/63628803.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定