我有這段代碼,可以為一定數(shù)量的物品輸入一個數(shù)字。每件商品的底價為 6.00 美元,然后根據(jù)商品數(shù)量對其應(yīng)用折扣,1-4 件商品無折扣,5-9 件商品有 10% 折扣,10-14 件商品有 14% 折扣, 15 人或以上可享受 20% 的折扣。我運行了這個程序,但它似乎輸出的是最終價格,沒有從總價中扣除折扣。我究竟做錯了什么? static void Main(string[] args) { int quantity; double price; quantity = GetQuantity(); price = CalculatePrice(quantity); WriteLine("Final price for {0} items is {1}.", quantity, price.ToString("c")); } private static int GetQuantity() { int quantity; Write("Enter number of items >> "); quantity = Convert.ToInt32(ReadLine()); return quantity; } private static double CalculatePrice(int quantityOrdered) { double PRICE_PER_ITEM = 6.00; double price = 0; double discount = 0; int[] quanLimits = { 0, 5, 10, 15 }; double[] limits = { 0, 0.10, 0.14, 0.20 }; for (int x = limits.Length - 1; x >= 0; x--) if (quantityOrdered >= quanLimits[x]) discount = limits[x]; //int x = 0; price = quantityOrdered * PRICE_PER_ITEM; price = price - (price * discount); return price; }
1 回答

藍山帝景
TA貢獻1843條經(jīng)驗 獲得超7個贊
您的具有內(nèi)部條件的 for 循環(huán)是錯誤的。它遍歷所有項目,并且由于給定數(shù)量始終 >=0(最后一個查詢是 quanLimits 數(shù)組中的第一個元素),最后一個賦值是 discount=0。這就是不計算折扣的原因。您可以通過反轉(zhuǎn) for 循環(huán)來解決這個問題,例如從索引 0 開始。
- 1 回答
- 0 關(guān)注
- 68 瀏覽
添加回答
舉報
0/150
提交
取消