项目实践问题:C#保龄球计分代码无法累计总分
搞定累计总分的问题!
嘿,我一眼就看出问题所在了——你的Tally方法里的result是局部变量,每次调用这个方法时,它都会被重新初始化回0,然后加上当前这一次的得分,所以返回的永远只是单轮分数,根本没法累计。
怎么解决?
要让总分在多次调用之间保持住,我们需要把存储总分的变量放在一个不会每次调用就销毁的地方,这里有两种简单的方案:
方案1:用静态字段存累计分
在Program类里加一个静态字段,这个字段会一直存在于程序运行过程中,每次调用Tally就往里面加分数就行。另外,别忘了每次开始新一局的时候把总分重置回0哦!
修改后的完整代码:
namespace TenPinBowling { class Program { // 静态字段,用来存全局的累计总分 private static int _totalScore = 0; static void Main(string[] args) { while (true) { Console.Write("Would you like to bowl, Y or N: "); // 加个Trim和ToLower,避免用户输入大小写或空格导致判断失效 var answer = Console.ReadLine()?.Trim().ToLower(); if (answer == "n") { Console.WriteLine("Thanks for playing, press any key to exit :)"); Console.ReadKey(); break; } // 新一局开始,重置总分 _totalScore = 0; Score(); } } static void Score() { // 把Random改成静态的,避免短时间多次调用生成重复随机数 static Random _pinsRandom = new Random(); // 保龄球单次最多击倒10个瓶,Next是左闭右开,所以范围是0到11 var pinsKnockedDown = _pinsRandom.Next(0, 11); Console.WriteLine("You bowled a: " + pinsKnockedDown); Console.WriteLine("Your total score is: " + Tally(pinsKnockedDown)); } static int Tally(int score) { // 把当前得分加到累计总分里 _totalScore += score; return _totalScore; } } }
方案2:用引用参数传递总分
如果你不想用静态字段,也可以把总分变量作为引用参数传给Tally方法,这样方法内部能直接修改外部变量的值:
namespace TenPinBowling { class Program { static void Main(string[] args) { while (true) { Console.Write("Would you like to bowl, Y or N: "); var answer = Console.ReadLine()?.Trim().ToLower(); if (answer == "n") { Console.WriteLine("Thanks for playing, press any key to exit :)"); Console.ReadKey(); break; } // 每局开始时初始化总分 int totalScore = 0; Score(ref totalScore); } } static void Score(ref int totalScore) { static Random _pinsRandom = new Random(); var pinsKnockedDown = _pinsRandom.Next(0, 11); Console.WriteLine("You bowled a: " + pinsKnockedDown); // 调用Tally更新总分 Tally(pinsKnockedDown, ref totalScore); Console.WriteLine("Your total score is: " + totalScore); } static void Tally(int score, ref int total) { total += score; } } }
小提醒
- 关于
Random:如果短时间内多次调用Score,每次都新建Random可能会生成相同的随机数,所以改成静态实例更靠谱。 - 你现在的代码只处理了一轮投球,后续可以根据保龄球的正式规则(10轮,全中、补中加分)来扩展
Score的逻辑哦!
内容的提问来源于stack exchange,提问作者curiouslyso
相关产品推荐
相关产品推荐

