0

Please take a look at the code first:

int result = 0;
result = Convert.ToInt32((correctAnswer / 5) * 100);

When I debug the program, Correct Answer get the value 4. But it doesn't pass the value to result. correctAnswer is intger, and I tried

result = ((correctAnswer / 5) * 100); 

I know there is simple error and I cannot seem to find it. Thank you

Gabriel Luci
  • 38,328
  • 4
  • 55
  • 84
newbie2
  • 25
  • 6
  • 2
    Pay attention, you are using integer division here. 4/5 = 0 * 100 = 0 – Steve Sep 10 '19 at 18:51
  • I assume that `correctAnswer`is declared as `int`. Then integer division is applied, and 4/5 = 0 (the remainder is discarded in integer division), 0*100 = 0 and `result` ends being 0 again. – Gian Paolo Sep 10 '19 at 18:52
  • if you change to `result = Convert.ToInt32((correctAnswer / 5d) * 100);` it will work. The `d` denotes a double value – DetectivePikachu Sep 10 '19 at 18:53

1 Answers1

0

Integer division discards decimals. You need to force it to use floating-point division by making at least one side of the division a floating-point number. Using 5.0 is enough to do that:

result = Convert.ToInt32((correctAnswer / 5.0) * 100);

Or, as mentioned in the comments, you can use 5d, which tells the compiler to make it a double. A full list of suffixes you can use are here

Gabriel Luci
  • 38,328
  • 4
  • 55
  • 84