变量之间计算的准确性有问题

Something is wrong with the accuracy of calculation between variables

我的代码有一些问题,我认为准确性有点偏差。我将从我的代码中取出变量的声明,所以代码尽可能小:

int a = Int32.Parse(tb_weight.Text);
double b = 0;
b = (a * 1.03) / 1000;
double g = 0;
g = (1.09 + (0.41 * (Math.Sqrt(50 / b))));
lbl_vertforce.Content = Math.Round((b * g * 9.81), 2);

所以,tb_weight 是一个文本框,输入是 5000,标签 lbl_vertforce 显示 119,61,根据我的计算器,它应该显示119,74。这里有什么问题?

双打并非 100% 精确,可能会在最不常见的数字上发生变化。如果你想要精确的精度,你需要使用 Decimal 类型,它有更大的内存占用,但设计得非常精确。不幸的是 Math.Sqrt 没有为 Decimal 超载并且只适用于双打。我提供了在另一篇讨论十进制平方根主题的帖子中找到的代码:Performing Math operations on decimal datatype in C#?

public void YourCodeModifiedForDecimal()
{
int a = Int32.Parse(tb_weight.Text);
decimal b = 0;
b = (a* 1.03m) / 1000m;
decimal g = 0;
g = (1.09m + (0.41m * (Sqrt(50m / b))));
lbl_vertforce.Content = Math.Round((b* g * 9.81m), 2);
}

public static decimal Sqrt(decimal x, decimal? guess = null)
{
    var ourGuess = guess.GetValueOrDefault(x / 2m);
    var result = x / ourGuess;
    var average = (ourGuess + result) / 2m;

    if (average == ourGuess) // This checks for the maximum precision possible with a decimal.
        return average;
    else
        return Sqrt(x, average);
}

您需要将g四舍五入到小数点后两位,最终计算得到119.74。

g = Math.Round(1.09 + (0.41 * (Math.Sqrt(50 / b))), 2);