Search code examples
c#mathncalc

Since when does 3 / 5 = 0?


So I've got a nice convoluted piece of C# code that deals with substitution into mathematical equations. It's working almost perfectly. However, when given the equation (x - y + 1) / z and values x=2 y=0 z=5, it fails miserably and inexplicably.

The problem is not that the values are passed to the function wrong. That's fine. The problem is that no matter what type I use, C# seems to think that 3/5=0.

Here's the piece of code in question:

public static void TrapRule(string[] args)
    {
        // ...

        string equation = args[0];
        int ordinates = Convert.ToInt32(args[1]);
        int startX = Convert.ToInt32(args[2]);
        int endX = Convert.ToInt32(args[3]);
        double difference = (endX - startX + 1) / ordinates;

        // ...
    }

It gets passed args as:

args[0] = Pow(6,[x])
args[1] = 5
args[2] = 0
args[3] = 2

(Using NCalc, by the way, so the Pow() function gets evaluated by that - which works fine.)

The result? difference = 0.

The same thing happens when using float, and when trying simple math:

Console.Write((3 / 5));

produces the same result.

What's going on?


Solution

  • The / operator looks at its operands and when it discovers that they are two integers it returns an integer. If you want to get back a double value then you need to cast one of the two integers to a double

    double difference = (endX - startX + 1) / (double)ordinates;
    

    You can find a more formal explanation in the C# reference