我正在尝试以已经格式化的方式打印我的乐透数字数组(来自我的Main
方法)中的数据(即4 7 19 23 28 36
在一行和下一行14 18 26 34 38 45
})等。
目前我似乎收到错误,我相信它告诉我该数组是错误的大小? (IndexOutOfRange
未处理)
static void Main() {
int[,] lottoNumbers = {
{ 4, 7, 19, 23, 28, 36},
{14, 18, 26, 34, 38, 45},
{ 8, 10, 11, 19, 28, 30},
{15, 17, 19, 24, 43, 44},
{10, 27, 29, 30, 32, 41},
{ 9, 13, 26, 32, 37, 43},
{ 1, 3, 25, 27, 35, 41},
{ 7, 9, 17, 26, 28, 44},
{17, 18, 20, 28, 33, 38},
};
int[] drawNumbers = new int[] {
44, 9, 17, 43, 26, 7, 28, 19 };
PrintLottoNumbers(lottoNumbers);
ExitProgram();
} // end Main
static void PrintLottoNumbers(int[,] lottoN) {
for (int i = 0; i < 8; i++){
for (int a = 0; a < 6; a++) {
Console.Write(lottoN[a, i]);
}
}
} // Print Function For Lotto Numbers
答案 0 :(得分:4)
请勿使用魔术数字! 8
或6
代表什么?
for (int i = 0; i < lottoN.GetLength(0); ++i) {
for (int j = 0; j < lottoN.GetLength(1); ++j)
Console.Write(lottoN[i, j]);
//DONE: you, probably, want to print out the array line by line
Console.WriteLine();
}
修改:您可能希望对齐数字,例如
4 7 19 23 28 36
14 18 26 34 38 45
而不是
4 7 19 23 28 36
14 18 26 34 38 45
在这种情况下,您必须提供格式,例如
Console.Write($"{lottoN[i, j],2}"); // ,2 - ensure length 2; align to the right
答案 1 :(得分:0)
如果要打印整个数组,则应按如下方式更改索引。
for (int i = 0; i < 8; i++){
for (int a = 0; a < 6; a++) {
Console.Write(lottoN[i, a]);
}
}
话虽如此,GetLength
方法,如上所述here,可用于读取多维数组的实际长度。