Java中编程求一个整数数组的最大值、最小值、平均值和所有数组元素的和

2024-11-25 13:48:58
推荐回答(3个)
回答1:

package
com.work20081209.main;
/**
*
Java中编程求一个整数数组的最大值、最小值、平均值和所有数组元素的和
*
*/
public
class
TestArray
{
private
int
maxValue;
private
int
minValue;
private
double
aveValue;
private
int
sumValue;
public
TestArray(int[]
nums){
maxValue
=
nums[0];
minValue
=
nums[0];
aveValue
=
nums[0];
sumValue
=
nums[0];
for
(int
i
=
1;
i
<
nums.length;
i++)
{
if(nums[i]
>
maxValue){
maxValue
=
nums[i];
}
if(nums[i]
<
minValue){
minValue
=
nums[i];
}
sumValue
=
sumValue
+
nums[i];
}
aveValue
=
sumValue/nums.length;
}
public
void
print(){
System.out.println("最大值:"+maxValue);
System.out.println("最小值:"+minValue);
System.out.println("平均值:"+aveValue);
System.out.println("和:"+sumValue);
}
public
static
void
main(String[]
args)
{
int[]
index
=
new
int[]{4,1,5,3,2};
TestArray
ta
=
new
TestArray(index);
ta.print();
}
}

回答2:

//求最小、最大、平均、和
public void test(int[] par) {
int min=par[0],max=par[0],sum=0,ave=0;
for(int i=0;i if(min>par[i])
min = par[i];
if(max max = par[i];
sum = sum + par[i];
}
ave = sum/par.length;
System.out.println("最小数:" + min);
System.out.println("最大数:" + max);
System.out.println("平均数:" + ave);
System.out.println("和:" + sum);
}

测试程序:
public void test(){
ArrayTest t = new ArrayTest();
int[] i = {1,2,3,4,5,6,7,8,31,12,5,36,54,5,753,42,4,231,34,22,3};
t.test(i);
}

回答3:

package com.test;
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
int[] score=new int[5];
int sum=0;//记录所以数据的和
for(int i=0;i<5;i++)
{
score[i]=i+1;
sum=sum+score[i];
}
Arrays.sort(score);//对数组进行升序排序
System.out.println(score[4]);//最大值
System.out.println(score[0]);//最小值
System.out.println(sum);//和
System.out.println(sum/score.length);//平均值

}
}
这是例子,基本上都有注释。不会可以继续问我281846610