0

I'm writting a calculator class that takes a math expression as string, solves it, and returns the result as double.

So far everything works as intended.

My problem is that one of my unit tests fails.

// this test should pass but fails with messag:
// Assert.AreEqual failed. Expected:<0,6000000000000001>. Actual:<1>. 
Assert.AreEqual(Solve("1 + 2 - 3 * 4 / 5"), ( 1 + 2 - 3 * 4 / 5));

You can test the problem with this code:

using System;

public class Program
{
    public static void Main()
    {
        double r = 1 + 2 - 3 * 4 / 5; // should be 0.6 or 0.6000000000000001
        Console.WriteLine(r == 1); // Prints True
        Console.WriteLine("Result: " + r); // Prints 1
    }
}

Fiddle https://dotnetfiddle.net/rRZtAu

How do i get the correct mathematical result?

Joshua Beckers
  • 857
  • 1
  • 11
  • 24

2 Answers2

2

You are getting 1 as a result because you are performing mathematical operations on all integer values.

If you want result in double, then you atleast one value should be double in division

try,

double r = 1 + 2 - 3 * 4 / 5.0;

Step by step execution,

= 1 + 2 - 3 * 4 / 5.0
       //^^^^  multiplication will execute first = 12
= 1 + 2 - 12 / 5.0
      //^^^^^^^^  this will return 2.4
= 1 + 2 - 2.4   
  //^^^^^^^  0.4

= 0.6  > result
Prasad Telkikar
  • 15,207
  • 5
  • 21
  • 44
2

If a and b are integers, then a / b is also an integer. If the result is not a whole number, it will be rounded towards zero.

1 + 2 - 3 * 4 / 5
= 1 + 2 - 12 / 5
= 1 + 2 - 2       // <-- 12 / 5 = 2.4, rounded to 2
= 1

It will only be cast to a double once you do the assignment, which is after the value has been computed.

To get the expected result, use a double in your division:

1 + 2 - 3 * 4 / 5.0
= 1 + 2 - 12 / 5.0
= 1 + 2 - 2.4       // <-- 12 / 5.0 = 2.4, not rounded since we're dividing by a double
= 0.6
Frxstrem
  • 38,761
  • 9
  • 79
  • 119