所以我有课程作业,我必须让用户在一个数组中键入值,得到平均值并输出高于或等于平均值的分数,以及低于平均值的分数。
但是,我只计算出平均值。
这是我到目前为止所做的:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter size of your array: ");
int n = sc.nextInt();
int a[] = new int[n];
System.out.println("Enter the test scores");
for(int i = 0; i < a.length; i++) {
a[i] = sc.nextInt();
}
int sum = 0;
for(int b=0; b < a.length; b++) {
sum = sum + a[b];
}
double average = ((double)sum) / a.length;
System.out.println("The average is"+" " + average);
}
我希望得到帮助,我输出的分数高于或等于平均分数和低于平均分数。
答案 0 :(得分:0)
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter size of your array: ");
int n = sc.nextInt();
int a[] = new int[n];
System.out.println("Enter the test scores");
for(int i = 0; i < a.length; i++)
{
a[i] = sc.nextInt();
}
int sum = 0;
for(int b=0; b < a.length; b++){
sum = sum + a[b];
}
double average = ((double)sum) / a.length;
int above = 0;
int below = 0;
for(int b=0; b < a.length; b++){
if ((double)a[b] > average) {
above++;
}
else if ((double)a[b] < average) {
below++;
}
}
System.out.println("The average is"+" " + average);
System.out.println("The count of numbers above average is " + above);
System.out.println("The count of number equal to average is " + (a.length - below - above));
System.out.println("The count of numbers below average is " + below);
}
}
答案 1 :(得分:0)
如果您希望将每个分数输出高于平均值,则将您的System.out行放入另一个for循环中,迭代数组,将每个元素与平均值进行比较。
实施例
System.out.print("Scores Above or Equal to the Average: ");
for(int i = 0, i < array.length, i++) {
if (array[i] >= average) {
System.out.print(array[i] + ", ");
} else {}
}
如果您试图获得高于或等于平均值的分数,基本上做同样的事情,但添加一个计数器变量
实施例
int scoresAbove = 0;
for(int i = 0, i < array.length, i++) {
if (array[i] >= average) {
scoresAbove ++;
} else {}
}
System.out.print("Number of Scores Above the Average: " + scoresAbove);
答案 2 :(得分:0)
添加如下代码块:
int numScoresAbove = 0;
for(int i = 0; i<a.length(); i++){
if(a[i]>=average){
numScoresAbove++
}
}
System.out.println("Number of scores above or equal to the average: "+numScoresAbove);
然后对不到一部分使用几乎相同的东西。