平均成绩(未显示成绩的平均值)

时间:2014-02-10 15:03:17

标签: java

制作一个程序,询问您将平均分数,然后输入成绩,它将添加并平均它们。我没有收到任何错误,但班级平均值无法正确显示。

import java.util.Scanner;

public class ExerciseFour
{
    public static void main( String[] args )
    {

        Scanner dylan = new Scanner(System.in);

        int total;
        int gradeCounter;
        int grade;      
        int average;    
        int numberofGrades;

        System.out.println("How many grades do you want to average?");
        numberofGrades = dylan.nextInt();



        total = 0;
        gradeCounter = 1;

        while ( gradeCounter <= numberofGrades )
        {
            System.out.println("Enter grade");
            grade = dylan.nextInt();
            total = total + grade;
            gradeCounter = gradeCounter +1;
        }


        average = total / numberofGrades;
        System.out.printf("The average is ", average );


    }

}

首先它要求输入多少,我按下4.我输入4,4,4,4,它出现了 “平均值是” 我希望它能显示成绩的平均值,有帮助吗? :d

2 个答案:

答案 0 :(得分:4)

变化:

System.out.printf("The average is ", average);

System.out.printf("The average is %lf", average);

或者

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

另请注意,您正在进行int次计算。 average应为double,您应该投一方:

average = (double)total / numberofGrades;

答案 1 :(得分:0)

printf非常适合格式化,因此如果您想将数字格式化为两位小数,则可以使用此方法:

System.out.printf("The average is %.2f", average );

%.2f说,“将此浮动格式化为两位小数。” (Further documentation

但是,如果您希望将此代码用于代码,则必须将average的声明更改为float

float average;

另请注意,您要划分的整数均为ints,因此您需要将此计算转换为float

average = (float) total / numberofGrades;