-8

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?

ArtOfCode
  • 5,702
  • 5
  • 37
  • 56

2 Answers2

6

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

Steve
  • 213,761
  • 22
  • 232
  • 286
1

They're called integers. Integers don't store any fractional parts of a number. Moreover, when you divide an integer divided by another integer... the result is still an integer.

So when you take 3 / 5 in integer land, you can't store the .6 result. All you have left is 0. The fractional part is always truncated, never rounded. Most programming languages work this way.

For something like this, I'd recommend working in the decimal type, instead.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794