猿问

没有数组的序列中的最大最小ODD数

我正在尝试从输入序列中获取最大和最小ODD数,而不使用数组,请告知我应该添加什么,我正在使用以下代码:


System.out.print("Enter odd integers(even to Stop): " );


do {

    num = input.nextInt();

    sum += num;

} while (num % 2 != 0);


if (num < min) {

    min = num;                

}

if (num > max) {

    max = num;

}


System.out.print("Minimum Odd Number: " + min + ";");

System.out.println("Maximum Odd Number: " + max);

System.out.print("Sum: " + sum);


慕桂英3389331
浏览 160回答 2
2回答

慕田峪4524236

您检查逻辑值,以可能将其记录为最小值或最大值的逻辑应该在循环内:int min = Integer.MAX_VALUE;int max = Integer.MIN_VALUE;int num = input.nextInt();while (num % 2 != 0) {&nbsp; &nbsp; sum += num;&nbsp; &nbsp; if (num < min) {&nbsp; &nbsp; &nbsp; &nbsp; min = num;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; }&nbsp; &nbsp; if (num > max) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;max = num;&nbsp; &nbsp; }&nbsp; &nbsp; num = input.nextInt();}System.out.print("Minimum Odd Number: " + min + ";");System.out.println("Maximum Odd Number: " + max);System.out.print("Sum: " + sum);作为注释,我将min和max分别初始化为最大和最小整数值。这样可以确保我们正确捕获最开始的输入,无论它们是什么。
随时随地看视频慕课网APP

相关分类

Java
我要回答