gpt4 book ai didi

c# - 输出行/列中的二维数组

转载 作者:太空宇宙 更新时间:2023-11-03 12:54:48 24 4
gpt4 key购买 nike

基本上,我有一个二维字符串数组,其中一个维度包含姓名,另一个维度包含一组成绩。尽我所能描述,我希望输出的名称是“标题”,每个名称的成绩都在该列中。

因此:

Name1 Name2
83 47
66 22

等等

我的代码如下:

static void Main(string[] args)
{
// Create a 2D array for names, and their grades
string[,] studentGrades = new string[5, 8];

// Set student names/grades manually
studentGrades[0, 0] = "Steve";
studentGrades[0, 1] = "69";
studentGrades[0, 2] = "80";
studentGrades[0, 3] = "66";
studentGrades[0, 4] = "75";
studentGrades[0, 5] = "90";
studentGrades[0, 6] = "69";
studentGrades[0, 7] = "98";

studentGrades[1, 0] = "Bob";
studentGrades[1, 1] = "73";
studentGrades[1, 2] = "67";
studentGrades[1, 3] = "65";
studentGrades[1, 4] = "91";
studentGrades[1, 5] = "48";
studentGrades[1, 6] = "33";
studentGrades[1, 7] = "94";

studentGrades[2, 0] = "Lewis";
studentGrades[2, 1] = "67";
studentGrades[2, 2] = "80";
studentGrades[2, 3] = "66";
studentGrades[2, 4] = "75";
studentGrades[2, 5] = "90";
studentGrades[2, 6] = "69";
studentGrades[2, 7] = "63";

studentGrades[3, 0] = "Sara";
studentGrades[3, 1] = "55";
studentGrades[3, 2] = "58";
studentGrades[3, 3] = "63";
studentGrades[3, 4] = "70";
studentGrades[3, 5] = "55";
studentGrades[3, 6] = "55";
studentGrades[3, 7] = "76";

studentGrades[4, 0] = "Xavier";
studentGrades[4, 1] = "22";
studentGrades[4, 2] = "27";
studentGrades[4, 3] = "25";
studentGrades[4, 4] = "19";
studentGrades[4, 5] = "42";
studentGrades[4, 6] = "18";
studentGrades[4, 7] = "32";

// Loop the array dimensions and output/format output the names/grades
for (int name = 0; name < studentGrades.GetLength(0); name++)
{
for (int grade = 0; grade < studentGrades.GetLength(1); grade++)
{
Console.WriteLine(studentGrades[name, grade]);
}
Console.WriteLine("");
}
}

编辑

输出是这样的:

Steve
69
80
....

Bob
73
67
....

等等

最佳答案

for (int grade = 0; grade < studentGrades.GetLength(1); grade++)
{
for (int name = 0; name < studentGrades.GetLength(0); name++)
{
Console.Write("{0, -15}", studentGrades[name, grade]);
}
Console.WriteLine();
}

上面的代码会给出这样的结果:

Steve          Bob            Lewis          Sara           Xavier
69 73 67 55 22
80 67 80 58 27
66 65 66 63 25
75 91 75 70 19
90 48 90 55 42
69 33 69 55 18
98 94 63 76 32

关于c# - 输出行/列中的二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34300172/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com