[How to program in C# YT tutorial] trying to display percentage of 6’s rolled

Updated on November 27, 2018 in [A] Brackeys Courses
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
1 on November 27, 2018

I am on video #7 “While Loops” and I was trying to display the percentage that we rolled a 6 but it comes out as 0.00 unless rolled on the first try, then displays 1.00 

Random numberGen = new Random();
int numberOfRolls = 0;
 int diceRoll = 0;
while (diceRoll != 6) {
 diceRoll = numberGen.Next(1, 7);
 Console.WriteLine("Tom rolled: " + diceRoll + ".");
 numberOfRolls++;
 }
 Console.WriteLine("It took Tom " + numberOfRolls + " rolls to get a six");
 float percentSix = 1 / numberOfRolls;
 string stringPercent = percentSix.ToString("f2");
 Console.WriteLine(stringPercent);
Console.ReadKey();

 

  • Liked by
Reply
0 on November 27, 2018

You’re dividing an int by an int. Even though you’re setting a float, this will still always and only return another int.

try adding ‘f’ after the 1 so it looks like:

float percentSix = 1f / numberOfRolls;

 

or, and I’m not 100% if this works because we’re casting after the fact, but you could try casting the whole thing as a float like this:

float percentSix = (float)(1 / numberOfRolls);

again I’m not 100% on this one, but the first way should work for sure.

  • Liked by
Reply
Cancel