c# - C# 中的数学错误

标签 c# math

我目前正在用 C# 编写 Shop 程序的代码。我是 C# 的新手,我很难在下面的代码中使用数学:

//Add Basket
public void addBasket()
{
   //Add up the total of individual items
   double total = 0;
   if (shoppingCart.Count() == 0)
   {
      Console.WriteLine("ERROR - Basket is Empty");
   }
   else
   {
      foreach (Products tmp in shoppingCart)
      {
         total = (tmp.Price * tmp.BoughtStock);
         Console.WriteLine("The cost of the individual item  is: " + "\t" +total);
      }
   }
   //Calculate the products together
   double itemTotal = 0;
   if (shoppingCart.Count() == 0)
   {
      Console.WriteLine("ERROR - Basket is Empty");
   }
   else
   {
      foreach (Products tmp in shoppingCart)
      {
         itemTotal = (tmp.Price * tmp.BoughtStock);
         itemTotal = itemTotal + total;
         Console.WriteLine("The cost of the items together is: \t" +itemTotal);
      }
      //Calculate VAT 
      double vatPrice = total * .21;
      double netPriceBeforeDiscount = total + vatPrice;

      //calculate discount: if total cost of shop is over 25 give 10% discount.
      if (netPriceBeforeDiscount >= 25)
      {
         double reducedPrice = netPriceBeforeDiscount * .10;
         double netPrice = netPriceBeforeDiscount - reducedPrice;
         reducedPrice = Math.Round(reducedPrice, 2);
         netPrice = Math.Round(netPrice, 2);

         Console.WriteLine("Discount*:\t\t\t\t " + reducedPrice);
         Console.WriteLine("\nTotal Net Cost (including VAT and discounts):\t      Euro " + netPrice);
      }
      else
      {
         double netPrice = Math.Round(netPriceBeforeDiscount, 2);
      }
   }
}

代码的第一部分工作正常,因为它添加了购物篮中的任何产品并单独显示价格,问题出现在第二部分,将购物篮中的商品价格加在一起。正如您在输出中看到的 http://gyazo.com/1656eecc689b7a9d0bfc47b8480169a6 (我必须链接输出的屏幕截图,因为我不知道如何在此处显示 C# 的输出)它显示第一项、第二项的总和,然后正确地将它们两个结果加在一起,尽管我不知道不知道为什么它显示第二个项目的成本乘以二。最后,正如您在代码底部看到的那样,我写了我认为是获取增值税和显示批量折扣的正确方法,但是从上面的链接来看,当我使用两个项目时,代码不会计算或显示增值税或批量折扣,但购物篮中只有一件商品,请参见此处 >(* 此处链接编号 1 *)。同样,根据我的想象,错误导致代码的其他部分无法正常工作,当我只做一件商品时,尽管正确计算了增值税和批量折扣并显示了正确的答案,它将单个商品的成本乘以金额关于我购买的产品,请参见此处 >(* 下面的链接编号 2 位于此处 *)

正如我所说,虽然我是新手,而且在 C# 方面也不是很好,但我们将不胜感激任何帮助,如果您需要我的任何东西,请直接询问,谢谢

编辑*:刚刚意识到我需要 10 个声誉才能发布两个以上的链接,我在下面的评论中链接了 2 个缺失的链接。

最佳答案

foreach (Products tmp in shoppingCart)
        {
            total = (tmp.Price * tmp.BoughtStock);

您的意思可能是total +=,否则您只保留最后一个值。

关于c# - C# 中的数学错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19847008/

相关文章:

c++ - 四元数和翻译

c# - .Net Core Api - 基于请求值的自定义 JSON 解析器

c# - 为什么在 Visual Studio 中调试时 Activator.CreateInstance 不传递构造函数异常?

c# - Microsoft Speech REST API 是否有音频长度限制

opengl - 纹理扭曲着色器 : Polar to Rectangular Coordinates

math - 正确的 glsl 仿射纹理映射

c# - SQL Server 2000 - 以编程方式限制对数据库所有者的访问?

c# - 在另一个 IDisposable "using"语句中处理 IDisposables

opencv - 从圆形照片定义 3D 场景

javascript - 大数 - JavaScript 中的数学