Java 这种小型for/if循环逻辑有什么问题?
这段代码询问用户将输入多少个数字,然后取其中的每一个。最后,它应该返回最小的值。我知道Math.min方法,我只是在努力解释为什么下面的逻辑不起作用,它总是打印最后一个输入,而不是最小的输入Java 这种小型for/if循环逻辑有什么问题?,java,Java,这段代码询问用户将输入多少个数字,然后取其中的每一个。最后,它应该返回最小的值。我知道Math.min方法,我只是在努力解释为什么下面的逻辑不起作用,它总是打印最后一个输入,而不是最小的输入 import java.util.Scanner; public class Ch5_smallestValue { public static void main(String[] args) { Scanner sc = new Scanner(System.in);
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);
}
}
import java.util.Scanner;
公共类Ch5_最小值{
公共静态void main(字符串[]args){
扫描仪sc=新的扫描仪(System.in);
System.out.println(“输入多少个数字,然后输入每个数字”);
int hMany=sc.nextInt();
int firstNum=sc.nextInt();
int最小=firstNum;
对于(int i=hMany;i>1;i--){
int input=sc.nextInt();
if(最小<输入){
最小=输入;
}
}
System.out.println(“最小=”+最小);
}
}
将(最小的(最小的>input)。条件不应该是最小的>input
?手动运行代码,您将能够自己找到此类错误。这是因为您在if
中的条件错误。查看上面的评论好的,非常感谢!这让人困惑,因为在我的头脑中,最小值应该比其他输入数值更小,即“<”而不是更大(>):)编辑:我现在就知道了:)