c#矩形数组有3个销售人员和5个产品

本文关键字:5个 数组 3个 | 更新日期: 2023-09-27 18:07:01

我一直得到索引超出范围异常。我必须得到销售人员编号和产品编号,然后是价格,然后才显示总数。

我不知道发生了什么,因为计算似乎是正确的。不管出了什么问题,都可能是我搞不明白的小事。谢谢你的帮助。

class Program
{
    static void Main(string[] args)
    {
        decimal[,] sales = new decimal[5, 3];
        int spnum;
        Console.WriteLine("Enter your Sales Person Number (type 999 to exit): ");
        spnum = Convert.ToInt32(Console.ReadLine());
        while(spnum != 999)
        {
            int prodnum;
            decimal price;
            decimal amount = 0;
        Console.WriteLine("Enter the product number: ");
        prodnum = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("Enter the total for the product: ");
        price = Convert.ToDecimal(Console.ReadLine());
        if (spnum >= 1 && spnum <= 3 && prodnum >= 1 && prodnum <= 5  && price >= 0)
        {
            sales[spnum - 1, prodnum - 1] += amount;
        }
        else
        {
            Console.WriteLine("You have entered an invalid number. Please try again.");
        }
        Console.WriteLine("Enter your salesperson (type 999 to exit): ");
        spnum = Convert.ToInt32(Console.ReadLine());
        }
        decimal[] total = new decimal[4];
        Console.WriteLine("'n{0,10}{1,16}{2,16}{3,16}{4,12}", "Product", "SalesPerson1", "SalesPerson2", "SalesPerson3", "Total");
              for (int row = 0; row < 5; row +=1)
        {
            decimal prodtot = 0M;
                  Console.Write("{0,10}", (row+=1));
                  for (int colum = 0; colum < 3; colum +=1)
                  {
                      Console.Write("{0,16:C}", sales[row, colum]);
                      prodtot += sales[row, colum];
                      total[colum] += sales[row, colum];
                  }
                  Console.Write("{0,10:C}", total);
                  for (int c = 0; c < 3; c += 1)
                  {
                      Console.Write("{0,16:C}", total[c]);
                      Console.ReadLine();
                  }
        }
    }

c#矩形数组有3个销售人员和5个产品

c#中的数组索引是基于0的。在您的例子中,它们从0到2和0到4。

销售声明为:

decimal[,] sales = new decimal[5, 3];

然后在这里使用它们:

if (spnum >= 1 && spnum <= 3 && prodnum >= 1 && prodnum <= 5  && price >= 0)
{
    sales[spnum - 1, prodnum - 1] += amount;
}

prodnum - 1可以大于2