0

When in a "challenge" in the app sololearn, answering C# related questions against each other, the question was "Are the outputs below going to be the same?"

Console.Write(5 / 2 + 2.5); // 4.5
Console.Write(5.0 / 2 + 2.5); // 5

When I run it it indeed gets different results (shown as comments in the code). Why the outputs of below is not the same?

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
Furnus
  • 19
  • 3
  • 5
    I will not give you the answer but here is a hint. 5.0.GetType().Name, 5.GetType().Name I am pretty sure you will be able to figure it out on you own from there – Filip Cordas Jun 11 '17 at 18:43

1 Answers1

2

In case of: Console.Write(5 / 2 + 2.5); The 5 / 2 is considered as integer/integer division. Check out this code:

    int i = 5;
    int j = 2;
    Console.WriteLine(i / j);
    //prints 2

In case of: Console.Write(5.0 / 2 + 2.5); The 5.0 / 2 is considered as double/integer division. Same code would be:

     double i = 5.0;
     int j = 2;
     Console.WriteLine(i / j);
     //prints 2.5

So in your case 5/2 + 2.5 results to 2 + 2.5 => 4.5

But in 5.0/2 + 2.5 we get 2.5 + 2.5 => 5

S_D
  • 226
  • 1
  • 8