2017-07-14 89 views
2

我有一個數學問題,我需要爲即將到來的C#基礎考試解決。下面的代碼是我迄今爲止完成的。讓我解釋一下代碼:百分比計算不正確

int capacity是足球場的容量。 [1..10000]

int fans是出席[1..10000]

for循環var sector是每個風扇的4個扇區之間的分配風扇的數量 - A,B,V,G

我需要計算每個扇區的風扇百分比以及所有風扇相對於體育場容量的百分比。

結果返回0.00的原因是什麼?

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace FootballTournament 
{ 
    class FootballTournament 
    { 
     static void Main(string[] args) 
     { 
      int capacity = int.Parse(Console.ReadLine()); 
      int fans = int.Parse(Console.ReadLine()); 

      int sector_A = 0; 
      int sector_B = 0; 
      int sector_V = 0; 
      int sector_G = 0; 

      for (int i = 0; i < fans; i++) 
      { 
       var sector = Console.ReadLine(); 
       if(sector == "A") 
       { 
        sector_A++; 
       } 
       else if (sector == "B") 
       { 
        sector_B++; 
       } 
       else if (sector == "V") 
       { 
        sector_V++; 
       } 
       else if (sector == "G") 
       { 
        sector_G++; 
       } 
      } 

      Console.WriteLine("{0:f2}%", (sector_A/fans * 100)); 
      Console.WriteLine("{0:f2}%", (sector_B/fans * 100)); 
      Console.WriteLine("{0:f2}%", (sector_V/fans * 100)); 
      Console.WriteLine("{0:f2}%", (sector_G/fans * 100)); 
      Console.WriteLine("{0:f2}%", (fans/capacity * 100)); 
     } 
    } 
} 

輸入/輸出例如:

Input: 
76 
10 
A 
V 
V 
V 
G 
B 
A 
V 
B 
B 

Output: 
20.00% 
30.00% 
40.00% 
10.00% 
13.16% 
+0

如果你不需要兩位小數,例如'sector_A * 100/fans',整數除法本身不會有問題。雖然沒有真正幫助你的具體情況。 – harold

回答

8

你正在做的整數運算。結果也將是一個整數。

將您的類型更改爲double,或將其轉換爲您的計算結果。

53/631 == 0 //integer 
53/631d == 0,0839936608557845 //floating point 
+0

好吧,它的工作!非常感謝你! – user3628807

1

您使用的是整數除法,其結果爲0

在你的榜樣,你正在使用int/int,這確實在整數運算的一切,即使你分配到十進制/雙精度/浮點變量。

強制其中一個操作數爲您要用於算術的類型。

decimal capacity = int.Parse(Console.ReadLine()); 
decimal fans = int.Parse(Console.ReadLine()); 

decimal sector_A = 0; 
decimal sector_B = 0; 
decimal sector_V = 0; 
decimal sector_G = 0; 
+0

謝謝你的回答!它也用'double'工作。 – user3628807

+0

@ user3628807如果您發現此回答有用,請接受並投票,以便其他用戶也可以將其識別爲有用的答案。謝謝你,不客氣。 –