如何计算平均分数?

时间:2015-11-22 15:52:50

标签: java eclipse

我制作直方图,收集学生成绩的结果,并显示哪些商标在一定范围内,例如0-29或70-100。

我试图找出如何编辑代码以便计算平均分数。我知道平均分数是通过添加所有数字并除以数字的数量来计算的,但我在将其实现到我的程序中时遇到了麻烦。

这是我的代码:

public static void main(String[] args) {

    int studentMark = 0;

    // ranges from (1)0-29, (2)30-39, (3)40-69, (4)70-100 (4 ranges)

    int firstRange = 0;         // (1)
    int secondRange = 0;        // (2)
    int thirdRange = 0;         // (3)
    int fourthRange = 0;        // (4)

    // counts all 'mark' attempts (except anything > 100)

    int numberOfStudents = 0;

    Scanner input = new Scanner(System.in);

    do{
        System.out.println("Enter a mark from 1-100: ");
        studentMark = input.nextInt();

    if (studentMark < 29) 
    {
        firstRange++;
        numberOfStudents++;
    }

    if ((studentMark > 29) && (studentMark <= 39)) 
    {
        secondRange++;
        numberOfStudents++;
    }

    if ((studentMark <= 69) && (studentMark > 39)) 
    {
        thirdRange++;
        numberOfStudents++;
    }

    if ((studentMark <= 100) && (studentMark > 69))
    {
        fourthRange++;
        numberOfStudents++;
    }


    }while ((studentMark <= 100))


    System.out.println("\nResults: \n");
    System.out.println("Number of students in total: " + numberOfStudents);
    System.out.println("\nStudents who ranged from 0-29: " + firstRange );
    System.out.println("Students who ranged from 30-39: " + secondRange);
    System.out.println("Students who ranged from 40-69: " + thirdRange);
    System.out.println("Students who ranged from 70-100: " + fourthRange);

    }

2 个答案:

答案 0 :(得分:0)

除了每个范围的计数外,您还需要保留所有成绩和总计数的总和(或者只添加单个范围总数)

答案 1 :(得分:0)

边境测试是红色的,至少有两个案例没有得到处理:
- rank = 29
- 排名&lt; 0

简化代码:

        // ranges from (1)0-29, (2)30-39, (3)40-69, (4)70-100 (4 ranges)
    final int[] roofs = new int[] {30, 40, 70, 101};
    final int[] compters = new int[roofs.length];
    final double[] sums = new double[roofs.length];
    final double[] means = new double[roofs.length];

    final Scanner input = new Scanner(System.in);
    do {
        System.out.println("Enter a mark from 0-100: ");
        final int studentMark = input.nextInt();
        int index = -1;

        if (studentMark < 0) {
            continue; // here to be ignored
        } else if (studentMark < roofs[0]) {
            index = 0;
        } else if (studentMark < roofs[1]) {
            index = 1;
        } else if (studentMark < roofs[2]) {
            index = 2;
        } else if (studentMark < roofs[3]) {
            index = 3;
        } else {
            break;
        }
        compters[index]++;
        sums[index] += studentMark;
    } while (true);
    input.close();

    final int numberOfStudents = Arrays.stream(compters).sum();
    IntStream.range(0, roofs.length).forEach(i -> means[i] = sums[i] / compters[i]);