-5
此代碼要求用戶輸入多少個數字,然後每個數字都需要輸入。最後它應該返回最小值。我知道Math.min方法,我只是爲了下面的邏輯不起作用而掙扎,它總是打印最後一個輸入,而不是最小的輸入。這個小的for/if循環邏輯有什麼問題?
import java.util.Scanner;
public class Ch5_smallestValue {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Input how many numbers and then input each one");
int hMany = sc.nextInt();
int firstNum = sc.nextInt();
int smallest = firstNum;
for (int i = hMany; i > 1; i--){
int input = sc.nextInt();
if (smallest < input){
smallest = input;
}
}
System.out.println("smallest = " + smallest);
}
}
不應該條件是'最小>輸入'?手動運行代碼,你將能夠自己發現這樣的錯誤。 – Codebender
它因爲你在'if'的條件是錯誤的。查看以上評論 –
好的,非常感謝!它的混亂雖然在我的頭最小值應該是更小,即「<」和不大於(>)比其他輸入數:)編輯:我現在得到它:) – ApRax