4 回答
TA贡献1866条经验 获得超5个赞
|是按位或运算符。您需要&&的是逻辑 AND 运算符。“如果number2大于number1 并且 number3大于number1。” 另外,您不希望if最后一个出现任何情况else,因为到那时您已经排除了三种可能性中的两种,只剩下一种可能性。
另外,我们要处理number1和number2相同且都低于 的情况number3。>=这可以通过使用而不是>第一个来完成if。
所以:
if (number2 >= number1 && number3 > number1) {
// −−−−−^−−−−−−−−−−^^
minimum = number1;
} else if (number1 > number2 && number3 > number2) {
// −−−−−−−−−−−−−−−−−−−−−−^^
minimum = number2;
} else /* No `if` here */ {
minimum = number3;
}
JavaScript 示例(因为上述逻辑和语法对于 Java 和 JavaScript 都是通用的):
function test(number1, number2, number3) {
let minimum;
if (number2 >= number1 && number3 > number1) {
// −−−−−−^−−−−−−−−−^^
minimum = number1;
} else if (number1 > number2 && number3 > number2) {
// −−−−−−−−−−−−−−−−−−−−−−^^
minimum = number2;
} else /* No `if` here */ {
minimum = number3;
}
console.log(minimum);
}
test(1, 2, 3); // Should be 1
test(3, 2, 1); // Should be 1
test(2, 2, 1); // Should be 1
test(2, 2, 4); // Should be 2
TA贡献1829条经验 获得超7个赞
也可以用import java.util.*女巫自带的java.lang.Math。这允许您使用来自的方法Math,例如Math.min。
import java.util.Scanner;
public class FindMin
{
public static void main(String[] args)
{
System.out.print("Program to compare three numbers");
System.out.println("and output minimum value entered");
Scanner input = new Scanner(System.in);
System.out.print("Enter 1st number: ");
int number1;
number1 = input.nextInt();
System.out.print("Enter 2nd number: ");
int number2;
number2 = input.nextInt();
System.out.print("Enter 3rd number: ");
int number3;
number3 = input.nextInt();
int minimum = Math.min(Math.min(number1, number2), number3);
System.out.print("The minimum of the numbers entered is ");
System.out.println(minimum);
System.out.println();
}
}
TA贡献1900条经验 获得超5个赞
尝试以下方法并将您的三个数字作为参数传递。
public static int getMinimumNumber(int no1, int no2, int no3) { return no1 < no2 ? (no1 < no3 ? no1 : (no2 < no3 ? no2 : no3)) : (no2 < no3 ? no2 : no3); }
TA贡献1851条经验 获得超3个赞
或者你可以这样做
int minimum = 0;
if(number1 < number2){
minimum = number1;
}else{
minimum = number2;
}
if(number3<minimum){
minimum = number3;
}
添加回答
举报