0
double celsius_0 = (100.5 - 32) * (5 / 9);
double celsius_1 = (100.5- 32) * 5 / 9;

Console.WriteLine(celsius_0);
Console.WriteLine(celsius_1);

output:
0
38,0555555555556

Why do they return differnt values? I dont understand whats happening

  • 1
    In the first case, `(5/9)` is evaluated, as integer division, hence resulting in `0` – Rafalon Feb 13 '22 at 13:53
  • 1
    Please read [Operator precedence](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/#operator-precedence) – Prasad Telkikar Feb 13 '22 at 13:54
  • If you really want to keep the brackets, change the number types for 5 and 9 from integers to doubles: `(5.0d / 9.0d)`. – myermian Feb 13 '22 at 13:55

1 Answers1

0

It's because here celsius_0 = (100.5 - 32) * (5 / 9) you count value in the first bracket then in the second one and then you multiply them.

While in the second line (100.5- 32) * 5 / 9 you count value in bracket then multiply it by 5 and at the end divide it by 9

To sum up in mathematics first you do things in brackets and then multiply/divide and finally add/substract

Prasad Telkikar
  • 15,207
  • 5
  • 21
  • 44
Kompocik
  • 55
  • 1
  • 8
  • The issue is actually due to type inference. The `(5 / 9)` is assumed to be an `int`, and `5/9` as an integer is indeed zero. Thus `100.5 - 32` multiplied by zero is zero. It's described more in depth in the duplicate answer. – Matt U Feb 13 '22 at 13:53
  • This code works, because every operation is converted to `double` implicitly. – Poul Bak Feb 13 '22 at 14:10
  • Oh yes, my bad guys. Didn't think about that – Kompocik Feb 13 '22 at 14:11