gpt4 book ai didi

java - 求数组的最大值

转载 作者:行者123 更新时间:2023-12-01 16:48:42 25 4
gpt4 key购买 nike

我正在尝试循环遍历数组以找到最大值并打印该值。但是,控制台上没有打印任何内容。您能看一下我下面的代码,看看我做错了什么吗?

for (c = 0; c < n; c++) //loops through array until each index has had a value input by the user
array[c] = in.nextInt();

maxInt = array[0];
minInt = array[0];

for (c = 0; c < n; c++) {
if (array[c] > maxInt) {
maxInt = array[c];
}
else {
break;
}
}
System.out.println("Max int is: " + maxInt);
}

编辑:

全类:

import java.util.Scanner;

public class MaxMinOfArray {
public static void main(String[] args) {
int c, n, search, array[];
int maxInt, minInt;

Scanner in = new Scanner(System.in);
System.out.println("Enter number of elements");
n = in.nextInt(); //asks user to specify array size
array = new int[n]; //creates array of specified array size

System.out.println("Enter " + n + " integers");

for (c = 0; c < n; c++) //loops through array until each index has had a value input by the user
array[c] = in.nextInt();

maxInt = array[0];
minInt = array[0];

for (c = 1; c < n; c++) {
if (array[c] > maxInt) {
maxInt = array[c];
}
}
System.out.println("Max int is: " + maxInt);
}
}

最佳答案

删除:

else {
break;
}

并从c=1开始

关于java - 求数组的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44991092/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com