您好,在我的程序中,我想显示数组中的平均数,最大数,最小数和模式。到目前为止,只有我的平均作品和我的min和max方法都是我输入的第一个数字。例如,如果我说我要输入3个数字并且我输入12,15和6.最小值和最大值都将输出12,因为它是输入的第一个数字,这是错误的所以请帮忙。这是我的代码。
int amount;
System.out.println(" Enter the amount of numbers you would like to enter: ");
amount = scan.nextInt();
int [] arr = new int [amount];
int outcome = 1;
for (int i = 0; i < arr.length; i++){
System.out.println("Enter a number 1 through 50");
outcome = scan.nextInt();
arr [i] = outcome;
}
System.out.println(" ");
System.out.println( " The average is" );
System.out.println(average(arr));
System.out.println(" ");
System.out.println( " The lowest value in the array is " );
System.out.println(min(arr));
System.out.println(" ");
System.out.println( " The largest value in the array is " );
System.out.println(max(arr));
System.out.println(" ");
}
public static double average ( int [] arr) {
double sum = 0;
int value = arr.length;
for ( int i = 0; i < arr.length; i++){
sum += arr [i];
}
sum = sum / value;
return sum;
}
public static int min (int [] arr) {
int shortest = 0;
int smallest = 100;
int length = arr.length;
for ( int i = 0; i < arr.length; i ++ ) {
if ( length < smallest)
shortest += arr[i];
smallest = arr.length;
}
return shortest;
}
public static int max (int [] arr) {
int largest = 0;
int biggest = 0;
int length = arr.length;
for ( int i = 0; i < arr.length; i ++ ) {
if ( length > largest)
biggest += arr[i];
largest = arr.length;
}
return biggest;
}
}
答案 0 :(得分:0)
这非常简单。你的min和max方法返回12的原因是因为你设置了arr.length的最大值和最小值,因此在一次运行后立即停止for循环。此外,这种问题的实现要容易得多。尝试沿着这些方向做点什么:
public int getMax(int[] arr)
{
int max = arr[0]; //To have a baseline
for(int i = 1; i < arr.length; i++)
{
if(arr[i] > max)
{
max = arr[i];
}
}
return max;
}
public int getMin(int[] arr)
{
int min = arr[0]; //To have a baseline
for(int i = 1; i < arr.length; i++)
{
if(arr[i] < min)
{
min = arr[i];
}
}
return min;
}
这更易读,更容易执行。只要问你是否有任何问题: - )