我一直让索引超出范围异常。在显示总数之前,我必须先获取销售人员编号和产品编号,然后再获取价格。
我不知道发生了什么,因为计算似乎是正确的。不管出了什么问题,可能都是一些小问题,我似乎就是搞不明白。感谢你的帮助。
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();
}
}
}发布于 2013-04-03 02:43:32
C#中的数组索引基于0。在您的例子中,它们从0到2和0到4运行。
发布于 2013-04-03 02:48:03
您可以将销售额声明为:
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。
https://stackoverflow.com/questions/15771857
复制相似问题