首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >C#矩形阵列有3个销售人员和5个产品

C#矩形阵列有3个销售人员和5个产品
EN

Stack Overflow用户
提问于 2013-04-03 02:42:10
回答 2查看 1.2K关注 0票数 0

我一直让索引超出范围异常。在显示总数之前,我必须先获取销售人员编号和产品编号,然后再获取价格。

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

代码语言:javascript
运行
复制
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();
                  }
        }

    }
EN

回答 2

Stack Overflow用户

发布于 2013-04-03 02:43:32

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

票数 2
EN

Stack Overflow用户

发布于 2013-04-03 02:48:03

您可以将销售额声明为:

代码语言:javascript
运行
复制
decimal[,] sales = new decimal[5, 3];

然后在这里使用它们:

代码语言:javascript
运行
复制
if (spnum >= 1 && spnum <= 3 && prodnum >= 1 && prodnum <= 5  && price >= 0)
{
    sales[spnum - 1, prodnum - 1] += amount;
}

prodnum - 1可以大于2。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15771857

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档