簡體   English   中英

分配值時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。 但是當我將這部分懸停時int d = Convert.ToInt32((Discount / 100) * ToDiscount); 沒有答案或沒有結果。

Discount / 100正在執行整數除法,結果為0。

因此(Discount / 100) * ToDiscount也為0,導致從ToDiscount中不減去任何東西。

我認為您最好的做法是將Discount的類型更改為decimal ,這將解決您那里的所有問題。

該行:

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

進行整數算術,對於零到99之間的任何折扣, Discount / 100將為零。

您需要通過十進制或浮點數來應用折扣:

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

順便說一句,命名變量Type可能會引起一些可讀性困擾。

當您這樣做時:Convert.ToInt32((Discount / 100)* ToDiscount); 您將擁有0,因為:

折扣/ 100 = 0(如果折扣為intm,則結果為int)

您應該使用雙數進行計算

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM