无限整数的平均值

时间:2014-08-04 02:10:56

标签: java

我的代码一直在说出每次输入后的平均值。我怎么能改变这一点,所以它只是在所有输入都很好之后才说出来....输入。

import java.util.Scanner;

public class RunGrades {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    System.out.println("Enter number of students");
    Scanner input = new Scanner(System.in);
    int X;
    X = input.nextInt();
    int grades[] = new int[X];

    for (int index = 0; index < grades.length; index++) {
        System.out.println("Enter student " + (index + 1) + "'s " + "grade");
        grades[index] = input.nextInt();
        System.out.println("The average grade is");
        double average;
        double total = 0;
        total += grades[index];
        average = total / X;
        System.out.println(average);
    }
}

}

3 个答案:

答案 0 :(得分:5)

你需要循环所有成绩

for(int i=0;i<grades.length;i++){

total+=grades[i];

}

average=total/x;

您的新代码将是

      double average;
        double total = 0;
  for (int index = 0; index < grades.length; index++) {
        System.out.println("Enter student " + (index + 1) + "'s " + "grade");
        grades[index] = input.nextInt();
        total += grades[index];
    }

        System.out.println("The average grade is");
        average = total / X;
        System.out.println(average);

        double average;
        double total = 0;
  for (int index = 0; index < x; index++) {
        System.out.println("Enter student " + (index + 1) + "'s " + "grade");
        total += input.nextInt();
    }

        System.out.println("The average grade is");
        average = total / X;
        System.out.println(average);

答案 1 :(得分:0)

您可以使用循环添加总计

double total = 0;
for (double g : grades) {
  total += g;
}
double average = (total / grades.length);

或者在输入上添加它们并使用一个循环(我会使用System.out.printf()) -

double total = 0;
for (int index = 0; index < grades.length; index++) {
  System.out.printf("Enter student %d's grade%n", index + 1);
  grades[index] = input.nextInt();
  total += grades[index];
}
double average = (total / grades.length);

答案 2 :(得分:0)

嗯......我认为你应该计算for循环之后的平均值。

double total = 0.0;
double average = 0.0;

for (int index = 0; index < grades.length; index++) {
    System.out.println("Enter student " + (index + 1) + "'s " + "grade");
    grades[index] = input.nextInt();
    total += grades[index];
}
average = total / grades.length; // Should calculate the last.

System.out.println("Average is "+average+".");

希望这会有所帮助......