c#定义一5*5的二维数组,数据自定义,完成以下操作: 1 计算两个对角线的和并输出 2 计算各各列的和并存储输出 3 将其转换为一维数组存储并输出
时间: 2024-10-29 17:17:21 浏览: 18
C#实现各种二维图形绘制
5星 · 资源好评率100%
在C#中,你可以使用`int[,]`来定义一个5x5的二维数组,并初始化数据。这里是一个例子:
```csharp
using System;
class Program
{
static void Main()
{
// 定义5x5的二维数组
int[,]' customArray = new int[5, 5]
{
{1, 2, 3, 4, 5},
{6, 7, 8, 9, 10},
{11, 12, 13, 14, 15},
{16, 17, 18, 19, 20},
{21, 22, 23, 24, 25}
};
// 计算对角线和并输出
int mainDiagonalSum = SumMainDiagonal(customArray);
Console.WriteLine("主对角线之和:{0}", mainDiagonalSum);
int secondaryDiagonalSum = SumSecondaryDiagonal(customArray);
Console.WriteLine("副对角线之和:{0}", secondaryDiagonalSum);
// 计算每一列的和
int[] columnSums = ColumnSums(customArray);
Console.WriteLine("各列和:");
for (int i = 0; i < columnSums.Length; i++)
{
Console.WriteLine("第{i}列:{0}", columnSums[i]);
}
// 转换为一维数组
int[] flattenedArray = Flatten(customArray);
Console.WriteLine("一维数组:");
foreach (int num in flattenedArray)
{
Console.Write(num + " ");
}
}
// 计算主对角线和
static int SumMainDiagonal(int[,] array)
{
int sum = 0;
for (int i = 0; i < array.GetLength(0); i++)
{
sum += array[i, i];
}
return sum;
}
// 计算副对角线和
static int SumSecondaryDiagonal(int[,] array)
{
int sum = 0;
for (int i = 0; i < array.GetLength(0); i++)
{
sum += array[i, array.GetLength(1) - i - 1];
}
return sum;
}
// 计算各列和
static int[] ColumnSums(int[,] array)
{
int[] sums = new int[array.GetLength(1)];
for (int j = 0; j < array.GetLength(1); j++)
{
int sum = 0;
for (int i = 0; i < array.GetLength(0); i++)
{
sum += array[i, j];
}
sums[j] = sum;
}
return sums;
}
// 二维数组扁平化为一维
static int[] Flatten(int[,] array)
{
int[] flattened = new int[array.GetLength(0) * array.GetLength(1)];
for (int i = 0; i < array.GetLength(0); i++)
{
for (int j = 0; j < array.GetLength(1); j++)
{
flattened[i * array.GetLength(1) + j] = array[i, j];
}
}
return flattened;
}
}
```
运行此代码后,你会得到对角线和、各列和以及一维数组的结果。
阅读全文