铸造会造成微小的价值差异吗?

时间:2017-09-07 18:38:15

标签: c# casting

我目前正在The Big List of Projects上编写更改退货程序,我的代码中遇到了逻辑错误。以下是相关代码段:

if(change / 1 >= 1) // checks if when divided the value is higher than 1, signaling that there is at least a dollar in change
{
    double temp1 = change % 1; // declared as double for casting
    temp1 = change - temp1; // and used to remove excess, non-dollar value
    dollarNum = (int) temp1;
    change -= (double)dollarNum;
}

如果更改为双倍,则此值为10.01。但是,在此代码段运行后,该值变为0.00999999999999979,而不是我想要的0.01。我在这里假设有什么问题吗?或者它完全是另一回事?

另请注意,我尝试将最后一行重新格式化为"更改=更改 - dollarNum并尝试使用dollarNum替换temp1以避免在该行中投射,但既没有解决这个问题。

如果我格式错误,请告诉我,我一定会尽快解决。

1 个答案:

答案 0 :(得分:2)

double不适合这种计算,因为它不会精确地存储值(在内部它使用二进制分数而不是十进制分数)。

使用'十进制'改为输入(https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/decimal):

        decimal change = 10.1M;
        if(change / 1 >= 1) //checks if when divided the value is higher than 1, signalling that there is at least a dollar in change
        {
            decimal temp1 = change % 1; //declared as double for casting
            temp1 = change - temp1; //and used to remove excess, non-dollar value
            int dollarNum = (int)temp1;
            change -= (decimal)dollarNum;
        }