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

本文关键字:数据类型 舍入 | 更新日期: 2023-09-27 17:50:51

我试图找到一个简单的MDAS(即乘法,除法…)问题的解决方案使用c#,虽然它大多得到正确的解决方案,我有问题,当变量加起来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,而不需要检查和修改值?如果不是,最好的方法是什么?

自动将.(9)舍入为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的rationalnuget包,并像这样使用它:

        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