无法正确显示百分比

时间:2016-06-07 11:03:42

标签: java

我似乎无法正确显示百分比。它每次循环时始终显示0.0。代码中的其他所有内容似乎都有效。

我可能错过了一些显而易见的东西,但在Java方面我有点像菜鸟,所以非常感谢任何帮助。

package e2E3;
import java.util.Scanner;

public class Main {

    public static void calculatePercentage(int studentMark, int maxMark){
        double percentage;
        percentage = studentMark / maxMark * 100;
        System.out.println("%" + percentage);

    }

    public static void totalAndAverageMark(){

            Scanner userInput = new Scanner(System.in);
            int numberOfStudents = 0;
            int maxMark = 0;
            int totalMark = 0;
            int studentCount = 0;
            int studentMark = 0;
            int average = 0;

            System.out.println("how many Students Sat the Test?");
            numberOfStudents = userInput.nextInt();

            System.out.println("what is the Maximum score?");
            maxMark = userInput.nextInt();

            do {

                System.out.println("enter students score..");
                studentMark = userInput.nextInt();

                calculatePercentage(studentMark, maxMark);

                totalMark = totalMark + studentMark;

                studentCount = studentCount + 1;

            } while (studentCount != numberOfStudents);

            average = totalMark / numberOfStudents;
            System.out.println("The Average Grade of Students was.. " + average);   

    }

    public static void main(String[] args) {

        totalAndAverageMark();

    }

}

1 个答案:

答案 0 :(得分:2)

您正在划分整数,因此结果始终是整数值。您可以将studentMark声明为double,它将按预期工作。如果你不想要这个,你可以在分区(double) studentMark / maxMark * 100;

中将它加倍