我有一个数学问题,我需要为即将到来的C#基础考试解决。下面的代码是我迄今为止所完成的。让我解释一下代码:
int capacity
是足球场的容量。 [1..10000]
int fans
是参加[1..10000]
var sector
循环中的 for
是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 :(得分:8)
你正在做整数数学。结果也将是一个整数。
将您的类型更改为double
,或将其投射到您的计算中。
实施例
53/631 == 0 //integer
53/631d == 0,0839936608557845 //floating point
答案 1 :(得分:1)
您正在使用整数除法,结果为0。
在您的示例中,您正在使用int/int
,即使您正在分配给decimal / double / float变量,它也会执行整数运算中的所有操作。
强制其中一个操作数属于您要用于算术的类型。
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;