c#中的折扣计算在分配值时出错

discount calculation in c# error on assigning value

有人能告诉我我的代码有什么问题吗?

我已经尝试先转换值,但我得到了相同的结果。

    /// <summary>
    /// Discount function
    /// </summary>
    /// <param name="ToDiscount">Price of an item</param>
    /// <param name="Discount">Discount</param>
    /// <param name="Type">Percent or Amount</param>
    /// <returns></returns>
    private decimal Discount(decimal ToDiscount, int Discount, DiscountType Type)
    {
        decimal temp = 0;
        try
        {
            if (Type == DiscountType.Percent)
            {
               int d = Convert.ToInt32((Discount / 100) * ToDiscount);
                decimal f = ToDiscount - d;
                temp = f;
            }
            else if (Type == DiscountType.Currency)
            {
                decimal FinalDiscount = ToDiscount - Discount;

                temp = FinalDiscount;
            }
        }
        catch (Exception ex)
        {
            Functions.ShowError(ex);
        }

        return temp;
    }

示例:

Discount(5000, 5, DiscountType.Percent);
//calculation: (5/100) * 5000 = 250
//discount: 5000 - 250 = 4750

但是使用我创建的函数得到的结果是 5000,而不是 4750。 我在 return temp 上做了断点;但是当我悬停这部分时 int d = Convert.ToInt32((Discount / 100) * ToDiscount); 没有答案或没有结果。

Discount / 100进行整数除法,结果为0。

因此 (Discount / 100) * ToDiscount 也是 0,导致 ToDiscount 没有减去任何内容。

我认为您最好的办法是将 Discount 的类型更改为 decimal,这将解决您的所有问题。

当你这样做时:Convert.ToInt32((Discount / 100) * ToDiscount); 你会有 0 因为:

折扣/100 = 0(如果折扣是 intm,结果将为 int)

你应该用双数进行计算

行:

int d = Convert.ToInt32((Discount / 100) * ToDiscount);

进行整数运算,其中 Discount / 100 对于 0 到 99 之间的任何折扣都将为零。

您需要通过小数或浮点数应用折扣:

int d = Convert.ToInt32((Discount / 100m) * ToDiscount);

顺便说一句,命名变量 Type 可能会导致一些可读性问题。