Why my C# code returns 0, if it must be 50 ?
double c = (1 / 2) * 100;
Console.WriteLine(c);
what is wrong?
1, 2 and 100, in your example, are all int literals. In C#, integer division returns integers, and ignores the remainder. Only after calculating 1/2 (=0) and multiplying by 100 (=0) does the result get converted to double
(1.0/2) * 100
Would give the expected result, because now 1.0 is a double literal, and forces the other literals to be converted to doubles also before the calculations are performed.
1 / 2 = 0
This is integer division.
Try 1.0 / 2, or why not double c = 50.0 directly ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With