2016-06-07 209 views
3

我似乎無法讓我的百分比正確顯示。每次循環時總是顯示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(); 

    } 

} 

回答

2

您正在分割整數,因此結果總是一個整數值。您可以將studentMark聲明爲double,並且可以按預期工作。如果你不想要這個,你可以在分區中將它投入兩倍(double) studentMark/maxMark * 100;