gpt4 book ai didi

java - 在java中从数组中查找最小值

转载 作者:行者123 更新时间:2023-12-04 15:43:10 26 4
gpt4 key购买 nike

我正在尝试从数组中的用户输入中获取总和、平均值、最大值和最小值。 sum、average 和 max 给出了正确的输出。但是最小值不起作用。我哪里做错了,有人可以帮我找出答案吗?

import java.util.Scanner;

public class minMaxSumAverage {
public static void main(String args[]) {
int n, sum = 0, max, min;
double average = 0;

Scanner s = new Scanner(System.in);
System.out.println("Enter elements you want to input in array: ");
n = s.nextInt();
int a[] = new int[n];
max = a[0];
min = a[0];
System.out.println("Enter all the elements:");
for (int i = 0; i < n; i++) {
a[i] = s.nextInt();
sum += a[i];
average = (double) sum/a.length;
if (a[i] > max) {
max = a[i];
}
if (a[i] < min) {
min = a[i];
}
}
System.out.println("Sum is: " + sum);
System.out.println("Average is: " + average);
System.out.println("Max is: " + max);
System.out.println("Min is: " + min);
}
}

输出:

Enter elements you want to input in array: 
5
Enter all the elements:
25
5
10
6
4
Sum is: 50
Average is: 10.0
Max is: 25
Min is: 0

最小值应为 4。

最佳答案

我已经更新了你的代码。请检查以下代码以从所有元素列表中获取最小值。

输入:

在数组中输入要输入的元素:

5

输入所有元素:

25

5

10

6

4

输出:

总数是:50

平均值为:10.0

最大值为:25

最小值为:4

        Scanner scan = null;
try {
int n, sum = 0, max, min;
double average = 0;
scan = new Scanner(System.in);
System.out.println("Enter elements you want to input in array: ");
n = scan.nextInt();
int a[] = new int[n];
max = a[0];
System.out.println("Enter all the elements:");
for (int i = 0; i < n; i++) {
a[i] = scan.nextInt();
sum += a[i];
average = (double) sum/a.length;
if (a[i] > max) {
max = a[i];
}
/**
// from here remove logic for get min value.
if (a[i] < min) {
min = a[i];
}
**/
}
min = a[0];
for(int i=0;i<a.length;i++){
if(a[i] < min){
min = a[i];
}
}
System.out.println("Sum is: " + sum);
System.out.println("Average is: " + average);
System.out.println("Max is: " + max);
System.out.println("Min is: " + min);
}
catch (Exception ex) {
ex.printStackTrace();
}finally{
scan.close();
}

关于java - 在java中从数组中查找最小值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56976805/

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