2017-07-14 87 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如果您发现此回答有用,请接受并投票,以便其他用户也可以将其识别为有用的答案。谢谢你,不客气。 –