如何用C#实现终端中不同位数数字的动态右对齐?
C#加减练习游戏数字右对齐实现方案
你当前的问题是数字位数不固定导致无法右对齐,核心是给数字字符串设置统一显示宽度并实现右对齐,C#里有两种简单可行的实现方式:
方法1:使用字符串插值的对齐格式
利用C#插值字符串的{变量名,宽度}语法,指定宽度后默认自动右对齐,直接修改打印逻辑的代码即可:
// 设置统一对齐宽度,这里设为8,足够容纳最大的三位数字(如100)和预留空格 int alignWidth = 8; Console.WriteLine($"{num1,alignWidth}\n+{num2,alignWidth-1}\n{new string('_', alignWidth)}");
这里num2的宽度设为alignWidth-1,是因为前面多了一个+符号,确保整体和第一行数字保持右对齐。
方法2:使用PadLeft方法
通过PadLeft给数字字符串左侧补空格,达到指定长度实现右对齐:
int totalWidth = 8; string num1Aligned = num1.ToString().PadLeft(totalWidth); // 第二行因为有"+ "前缀,数字部分需要的宽度是totalWidth - 2 string num2Aligned = num2.ToString().PadLeft(totalWidth - 2); Console.WriteLine($"{num1Aligned}\n+ {num2Aligned}\n{new string('_', totalWidth)}");
修改后的完整代码
/* 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); // 确保num1大于num2,符合需求注释里的要求 if (num2 > num1) { (num1, num2) = (num2, num1); } answer = num1 + num2; // 使用方法1的对齐方式 int alignWidth = 8; Console.WriteLine($"{num1,alignWidth}\n+{num2,alignWidth-1}\n{new string('_', alignWidth)}"); 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");
额外补充了交换num1和num2的逻辑,确保num1始终大于num2,匹配你注释里的需求。
内容的提问来源于stack exchange,提问作者Michael McKeehan
相关产品推荐
相关产品推荐

