自动将 .(9) 舍入为 1 的数据类型?

Data type that rounds .(9) to 1 automatically?

我正在尝试使用 C# 寻找简单的 MDAS(即乘法、除法...)问题的解决方案,虽然它大部分都能得到正确的解决方案,但当变量加起来达到 x.99999 时我会遇到问题。 .. 所以我得到了错误的答案,因为它没有计算为 1.

例如,如果我有:

        decimal a = 1M;
        decimal b = 2M;
        decimal c = 6M;
        decimal d = 4M;
        decimal e = 7M;
        decimal f = 8M;
        decimal g = 3M;
        decimal h = 5M;
        decimal i = 9M;
        Console.WriteLine(a + 13 * b / c + d + 12 * e - f - 11);
        Console.WriteLine(g * h / i);
        Console.WriteLine(a + 13 * b / c + d + 12 * e - f - 11 + g * h / i);

这给了我:

74.33333333333333333333333333
1.6666666666666666666666666667
75.999999999999999999999999997

但我想要:

74.33333333333333333333333333
1.6666666666666666666666666667
76

有没有一种方法可以让我始终得到 .(6)+.(3) = 1 的精确答案,而无需检查和修改值?如果不是,最好的方法是什么?

以下内容会将您的 double 值四舍五入到精度为 0.1 的范围内:

// parameters
double d = -7.9;
double precision = 0.1;

//the conversion
double v = (Math.Abs(Math.Round(d)-d)) < precision ? Math.Round(d) : d;

//output
int i = (int) v;
Console.WriteLine(i);

我接受了@tia 和 Dai 的建议,使用 Rational 数据类型。我得到了 tompazourek's Rationals NuGet package 并像这样使用它:

        Rational a = 1;
        Rational b = 2;
        Rational c = 6;
        Rational d = 4;
        Rational e = 7;
        Rational f = 8;
        Rational g = 3;
        Rational h = 5;
        Rational i = 9;
        Console.WriteLine(a + (Rational)13 * b / c + d + (Rational)12 * e - f - (Rational)11);
        Console.WriteLine(g * h / i);
        Rational toTest = a + (Rational)13 * b / c + d + (Rational)12 * e - f - (Rational)11 + g * h / i;
        Console.WriteLine(toTest);
        Console.WriteLine(toTest.Equals(76)); 

这给了我:

446/6
15/9
4104/54
True