2015-08-21 65 views
-5

我開始學習C#,這裏是一個使用System計算百分比 的程序;在C#中計算百分比

namespace CheckDegree 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      int totalmarks=0; 
      for (int i = 0; i < 5; i++) { 
      Console.WriteLine("Please enter a subject."); 
      string subject = Console.ReadLine(); 
      Console.WriteLine("Enter the mark for {0}",subject); 
      int mark = Convert.ToInt32(Console.ReadLine()); 
      totalmarks = totalmarks + mark; 
      } 
      double percentage = (totalmarks/500) * 100; 
      if (percentage >= 60) 
      { 
       Console.WriteLine("You got {0} and has been awarded a first division", percentage); 
      } 
      else if (percentage >= 50 && percentage <= 59) 
      { 
       Console.WriteLine("You got {0} and has been awarded a second division", percentage); 
      } 
      else if (percentage < 40) 
      { 
       Console.WriteLine("You got {0} and thus have failed!!!", percentage); 
      } 
      Console.ReadKey(); 
     } 
    } 
} 

然而percentage總是輸出0

double percentage = (totalmarks/500) * 100; 

回答

2

代替通過500,除法除以500.0的。它將其視爲一個整數除以整數,這將是0。#####。由於它是一個整數,所以小數點被丟棄。然後,0次100仍然爲0.

將500更改爲500.0將強制劃分爲double,這將保留您的小數值。

+0

Arghh ,,,,,,,謝謝 – user2650277