二维数组:
public static void Main(string[] args)
{
int[,] a = new int[3, 3];
Random rom = new Random();
for (int x = 0; x < a.GetLength(0); x++)
{
for (int y = 0; y < a.GetLength(1); y++)
{
a[x, y] = rom.Next(31);
Console.Write("{0} ", a[x, y]);
}
Console.WriteLine("");
}
}
// 求矩阵对角线之和
public static void Main(string[] args)
{
int[,] a= new int[3, 3];
Random rnd = new Random();
int a1 = 0;
int a2 = 0;
for (int x = 0; x < a.GetLength(0); x++)
{
for (int y = 0; y < a.GetLength(1); y++)
{
a[x, y] = rnd.Next(21);
Console.Write("{0} ", a[x, y]);
if (x == y)
{
a1 += a[x, y]; //统计正对角线元素之和
}
if (x + y == a.GetLength(0) - 1)
{
a2 += a[x, y]; //统计副对角线元素之和
}
}
Console.WriteLine("");
}
Console.WriteLine("正对角线元素之和:{0}", a1);
Console.WriteLine("副对角线元素之和:{0}", a2);
}
原文:https://www.cnblogs.com/yijieyufu/p/11902017.html