提问人:Michael McKeehan 提问时间:9/21/2023 更新时间:9/21/2023 访问量:48
将终端中的字符串与 c 对齐#
Aligning strings in the terminal with c#
问:
我正在寻找一点帮助。我是 C# 的新手,正在尝试为我的孩子构建一个简单的加法/减法游戏来练习他的技能。到目前为止,我已经掌握了基础知识(需要进一步开发),但有一个问题需要解决。
我如何设置代码中的字符串,它将在单独的行上打印几个随机数。我想将这些数字向右对齐,但并不总是有固定的数字数。这是到目前为止的代码(可能很草率,所以我很抱歉)。
/* Basic build
- There are two numbers up to 6 numbers
- Number 1 must be higher than number 2 (-'s are still out of scope)
- Operation is randomized
- 10 Questions per round
- There will need to be a scoring system
*/
int num1;
int num2;
int answer;
string opperation = "+";
string guess;
int finalAnswer;
Random randNumber = new Random();
int score = 0;
for (int i = 0; i < 10; i++)
{
num1 = randNumber.Next(0, 101);
num2 = randNumber.Next(0, 101);
string num1String = num1.ToString();
string num2String = num2.ToString();
answer = num1 + num2;
Console.WriteLine($" {num1String}\n+ {num2String}\n---------");
guess = Console.ReadLine();
while (!int.TryParse(guess, out finalAnswer))
{
Console.WriteLine("That is not a valid number. Please guess again:");
guess = Console.ReadLine();
}
if (finalAnswer == answer)
{
score++;
Console.WriteLine("That is correct! :)\n\n");
}
else
{
Console.WriteLine("That is Incorrect. :(\n\n");
}
}
Console.WriteLine($"Your score is {score} out of 10");
当前输出的一个例子可以是
100
+ 5
_________
我希望让它更像
100
+ 5
_________
我一直在研究,但无法找到解决方案。
答:
1赞
Martin Honnen
9/21/2023
#1
例如,做
Console.WriteLine(" {0,8}\n+ {1,8}\n----------", num1, num2);
应该会有所帮助。
评论
0赞
chux - Reinstate Monica
9/21/2023
通常,字符串长度为 1 到 11 个字符。 可能不足。int
8
0赞
Martin Honnen
9/21/2023
我认为结果不会是 11 个字符。但无论如何,只是想根据问题中的示例代码显示一些示例,使用可能的格式选项。randNumber.Next(0, 101);
0赞
chux - Reinstate Monica
9/21/2023
公平点.....
2赞
Frosch
9/21/2023
#2
字符串类有一个可以使用的内置方法。PadLeft
例如:
Console.WriteLine($"{num1String.PadLeft(10)}\n{operation}{num2String.PadLeft(10 - operation.Length)}\n---------");
我使用了您定义的变量,并且在确定 的填充时考虑了它的长度。operation
num2String
评论
0赞
Michael McKeehan
9/21/2023
这很顺利,谢谢@Frosch
评论