【发布时间】:2015-05-02 11:47:15
【问题描述】:
请帮忙。被此代码卡住尝试了不同的方法,但无法使其正常工作。我有一个“foreach”循环,从技术上讲,它必须对 2D 数组中的所有整数求和,但是,计算出的答案不是预期的。我究竟做错了什么?谢谢谢谢。
static void Main(string[] args)
{
const int ROWS = 2;
const int COLS = 2;
const int MAX = 5;
string input;
int[,] numbers = new int[ROWS, COLS];
do
{
int total = 0;
double avg = 0;
Random rand = new Random();
for (int rows = 0; rows < ROWS; ++rows)
{
for (int cols = 0; cols < COLS; ++cols)
{
numbers[rows, cols] = rand.Next(1, MAX);
}
{
for (int cols = 0; cols < COLS; ++cols)
Console.Write(" {0, 3}", numbers[rows, cols]);
Console.WriteLine();
}
foreach (int cell in numbers)
{
total += cell;
}
avg = total / 4.0;
} Console.WriteLine("Sum: {0:0,0} Average: {1:f}", total, avg);
Console.Write("\nWould you like to generate a new table? Type yes or no... ");
input = Console.ReadLine().ToLower();
if (input == "no")
{
Console.WriteLine("End of program. Press any key to exit. Goodbye.");
}
}
while (input == "yes");
Console.ReadKey();
【问题讨论】:
标签: c loops multidimensional-array foreach sum