【问题标题】:Correctly deducting a discount from a total price? [closed]从总价中正确扣除折扣? [关闭]
【发布时间】:2019-09-11 00:20:17
【问题描述】:

我有这个代码,它包含一个数量的项目。每件商品的底价为 6.00 美元,然后根据商品的数量对其应用折扣,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;
    }

【问题讨论】:

  • 你调试过你的代码吗,哪一行,哪里出错了?

标签: c# loops percentage price


【解决方案1】:

带有内部条件的 for 循环是错误的。它遍历所有项目,并且由于给定数量始终 >=0(最后一个查询是 quanLimits 数组中的第一个元素),因此最后一个分配是 discount=0。这就是为什么不计算折扣的原因。 您可以通过反转 for 循环来解决此问题,例如从索引 0 开始。

【讨论】:

  • 谢谢!我是新来的,感谢您的回复!
  • 欢迎您!如果它有助于解决您的问题,您可以将其标记为已接受的答案(旁边带有 ceck 符号)。编码愉快!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-29
  • 2011-12-16
  • 1970-01-01
相关资源
最近更新 更多