C# and Python result difference – basic Math

Question:

So I have tried the same math in c# and python but got 2 different answer. can someone please explain why is this happening.

def test():
l = 50
r = 3
gg= l + (r - l) / 2
mid = l + (r - l) // 2
print(mid)
print(gg)

public void test()
    {
        var l = 50;
        var r = 3;
        var gg = l + (r - l) / 2;

        double x = l + (r - l) / 2;
        var mid = Math.Floor(x);
        Console.WriteLine(mid);
        Console.WriteLine(gg);
    }
Asked By: Attiq Rahman

||

Answers:

In C#, the / operator performs integer division (ignores the fractional part) when both values are type int. For example, 3 / 2 = 1, since the fractional part (0.5) is dropped.

As a result, in your equation, the operation (r - l) / 2 is evaluating to -23, since (3 - 50) / 2 = -47 / 2 = -23 (again, the fractional part is dropped). Then, 50 + (-23) = 27.

However, Python does not do this. By default, all division, whether between integers or doubles, is "normal" division – the fractional part is kept. Because of that, the result is the same as you’d get on a calculator: 50 + (3 - 50) / 2 = 26.5

If you want C# to calculate this the same way as Python, the easiest way is to make one of the numbers a double. Adding .0 to the end of the divisor should do the trick:

// changed '2' to '2.0'
var gg = l + (r - l) / 2.0;
double x = l + (r - l) / 2.0;

26
26.5

Answered By: Caleb Keller
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.