用户输入整数,程序确定偶数最大值和偶数和。
程序输出是正确的,但最后出现错误,显示“超时(无限循环?)”。有什么办法可以结束循环吗?
static void evenSumMax() {
Scanner sc = new Scanner(System.in);
System.out.print("how many integers? ");
int size = sc.nextInt();
int integer[] = new int[size];
int sum = 0;
int max = 0;
for (int i = 0; i < size; i++) {
System.out.print("next integer? ");
integer[i] = sc.nextInt();
if (integer[i] > 0 && integer[i] % 2 == 0) {
sum += integer[i];
if (integer[i] > max) {
max = integer[i];
}
}
}
System.out.println("even sum = " + sum);
System.out.println("even max = " + max);
}
❌ You passed 0 of 3 tests. Try again.
test #1: 4 (2, 9, 18, 4)
expected output:
how many integers? 4
next integer? 2
next integer? 9
next integer? 18
next integer? 4
even sum = 24
even max = 18
your output:
*** TIMEOUT (infinite loop?)
how many integers? 4
next integer? 2
next integer? 9
next integer? 18
next integer? 4
even sum = 24
even max = 18
differences:
0a1
> *** TIMEOUT (infinite loop?)
result:
❌ fail
details:
exceeded maximum allowed run time
我在线尝试了不同的编译器,他们没有给我这个问题。
您只能在设置数组值后立即使用数组中的最后一个值。这意味着对于大输入,您的程序首先需要分配一个huge数组。根据运行时环境,这可能会崩溃或需要很长时间。
摆脱数组,只需将“下一个整数”存储在单个
int
变量中。使用该单个变量来计算总和和最大值。您不需要超过 4 个变量:size
、nextInteger
、sum
、max
。
如果这不起作用,请咨询您的教练。