Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

arithmetic operation in C#

Tags:

c#

.net

Why my C# code returns 0, if it must be 50 ?

double c = (1 / 2) * 100;
Console.WriteLine(c); 

what is wrong?

like image 787
Wachburn Avatar asked Mar 08 '26 12:03

Wachburn


2 Answers

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.

like image 146
Damien_The_Unbeliever Avatar answered Mar 10 '26 03:03

Damien_The_Unbeliever


1 / 2 = 0

This is integer division.

Try 1.0 / 2, or why not double c = 50.0 directly ;)

like image 37
Petar Ivanov Avatar answered Mar 10 '26 03:03

Petar Ivanov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!