This is driving me nuts... I'm trying to complete a very simple assignment, but I can't seem to get past this issue I'm having with decimals getting chopped off.
Here's my code. I've pasted the actual assignment itself and commented it out, so you can see what I'm trying to do. Keep in mind this is a pretty basic assignment, and it's just a quick console app, so there is no error-handling or crash-proofing.
Code:
static void Main(string[] args)
{
//Use random numbers to simulate the repeated tossing of a fair coin.
//Letting the user input the number of tosses, report the percentage of outcomes that are heads.
//Allow the user to repeat the calculation as often as desired.
string again;
Random rnd = new Random();
do
{
int heads = 0;
int tails = 0;
int numOfTosses = 0;
Console.Write("How many tosses would you like to make? ");
numOfTosses = int.Parse(Console.ReadLine());
int tossCount = numOfTosses;
while (tossCount > 0)
{
int toss = rnd.Next(1, 3);
if (toss == 1)
heads++;
else
tails++;
tossCount--;
}
Console.WriteLine("Number of Heads: {0} ({1}%).", heads, (heads / numOfTosses) * 100);
Console.WriteLine("Number of Tails: {0} ({1}%).", tails, (tails / numOfTosses) * 100);
Console.WriteLine("");
Console.Write("Toss again? (yes/no) ");
again = Console.ReadLine();
Console.WriteLine("");
}
while (again == "yes");
}
The problem is that I'm trying to get the following bit:
Code:
Console.WriteLine("Number of Heads: {0} ({1}%).", heads, (heads / numOfTosses) * 100);
Console.WriteLine("Number of Tails: {0} ({1}%).", tails, (tails / numOfTosses) * 100);
To show a proper %, but it keeps truncating the decimal and then multiplying by zero. So, instead of (16 / 25) * 100 returning 64, it's just returning 0 (because it's taking 16/25=0.64 and truncating the .64, leaving only a 0... and then multiplying it by 100).
I know it has something to do with type (int, double, float, etc). I can get it to work perfectly, if I change everything from int to double, but there has to be a way to leave my int types alone and still get this number to print properly...
As a workaround, I'm using {(heads * 100) / numOfTosses}, but even that isn't working as it's still truncating the decimal in the calc and returning two % that don't add up to 100 (like 73% and 26%).