How should I compare these doubles to get the desi

2019-07-30 11:10发布

I have a simple example application here where I am multiplying and adding double variables and then comparing them against an expected result. In both cases the result is equal to the expected result yet when I do the comparison it fails.

static void Main(string[] args)
{
    double a = 98.1;
    double b = 107.7;
    double c = 92.5;
    double d = 96.5;

    double expectedResult = 88.5;
    double result1 = (1*2*a) + (-1*1*b);
    double result2 = (1*2*c) + (-1*1*d);            

    Console.WriteLine(String.Format("2x{0} - {1} = {2}\nEqual to 88.5? {3}\n", a, b, result1, expectedResult == result1));
    Console.WriteLine(String.Format("2x{0} - {1} = {2}\nEqual to 88.5? {3}\n", c, d, result2, expectedResult == result2));

    Console.Read();
}

And here is the output:

2x98.1 - 107.7 = 88.5
Equal to 88.5? False

2x92.5 - 96.5 = 88.5
Equal to 88.5? True

I need to be able to capture that it is in fact True in BOTH cases. How would I do it?

7条回答
相关推荐>>
2楼-- · 2019-07-30 12:02

If you need more precision (for money and such) then use decimal.

var a = 98.1M;
var b = 107.7M;
var c = 92.5M;
var d = 96.5M;

var expectedResult = 88.5M;
var result1 = (2 * a) + (-1 * b);
var result2 = (2 * c) + (-1 * d);

Console.WriteLine(String.Format("2x{0} - {1} = {2}\nEqual to 88.5? {3}\n", a, b, result1, expectedResult == result1));
Console.WriteLine(String.Format("2x{0} - {1} = {2}\nEqual to 88.5? {3}\n", c, d, result2, expectedResult == result2));

Output:

2x98.1 - 107.7 = 88.5
Equal to 88.5? True

2x92.5 - 96.5 = 88.5
Equal to 88.5? True
查看更多
登录 后发表回答