我做得对吗?我正在尝试将这个二维数组的每个数字相加,并显示总数。我认为我走在了正确的轨道上,但如果有人能帮助我,我会非常感激。
int[,] A = new int[3, 4]
{
{ 4, -5, 12, -2},
{ -9, 15, 19, 6},
{ 18, -33, -1, 7}
};
private void TotArray(int[,] array)
{
int sum = 0;
int rows = array.GetLength(0);
int cols = array.GetLength(1);
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
sum += A[i, j];
}
}
}
private void button1_Click(object sender, EventArgs e)
{
TotArray(A);
}
您忽略了sum
变量,您应该从方法中返回它。除此之外,您的方法看起来还不错。还请记住,您可以始终使用LINQ
进行这种操作:
var sum = A.OfType<int>().Sum();
如果您想在末尾显示总和:
int[,] A = new int[3, 4]
{
{ 4, -5, 12, -2},
{ -9, 15, 19, 6},
{ 18, -33, -1, 7}
};
private void TotArray(int[,] array)
{
int sum = 0;
int rows = array.GetLength(0);
int cols = array.GetLength(1);
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
sum += A[i, j];
}
}
MessageBox.Show("The sum of the array is " + sum.ToString() + "."); //Show the sum
}
private void button1_Click(object sender, EventArgs e)
{
TotArray(A);
}