在一个 15 益智游戏的数组上强制输入两位数字
force two digits on an array for a 15 puzzle game
我正在为学校制作一个 15 位益智游戏,但现在它只有 9 个数字,但如果我添加 2 位数字,它会弄乱整个网格。所以我希望所有数字都有2位数字(2→→02)。
int[,] tab = { { 2, 1, 7 }, { 6, 9, 4 }, { 3, 0, 7 } };
显示数字时,格式化字符串。这是一个例子:
int value = 2;
string result = String.Format("{0,2:00}", value);
Console.WriteLine(result);
该示例显示以下输出:
02
由于您使用的是二维数组,因此您可以这样做:
int[,] tab = { { 2, 1, 7 }, { 6, 9, 4 }, { 3, 0, 7 } };
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
Console.Write(String.Format("{0,2:00} ", tab[i,j]));
}
Console.Write("\n");
}
这里我们使用 String.Format 将数字打印为两位数。由于 table 中的整数只有一位,因此会自动添加前导零。因此,对于您的代码,输出将是:
02 01 07
06 09 04
03 00 07
我正在为学校制作一个 15 位益智游戏,但现在它只有 9 个数字,但如果我添加 2 位数字,它会弄乱整个网格。所以我希望所有数字都有2位数字(2→→02)。
int[,] tab = { { 2, 1, 7 }, { 6, 9, 4 }, { 3, 0, 7 } };
显示数字时,格式化字符串。这是一个例子:
int value = 2;
string result = String.Format("{0,2:00}", value);
Console.WriteLine(result);
该示例显示以下输出:
02
由于您使用的是二维数组,因此您可以这样做:
int[,] tab = { { 2, 1, 7 }, { 6, 9, 4 }, { 3, 0, 7 } };
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
Console.Write(String.Format("{0,2:00} ", tab[i,j]));
}
Console.Write("\n");
}
这里我们使用 String.Format 将数字打印为两位数。由于 table 中的整数只有一位,因此会自动添加前导零。因此,对于您的代码,输出将是:
02 01 07
06 09 04
03 00 07