# 猜数字 使用C#编写一个猜数字游戏,以下实现没有错误的代码是? ## 答案 ```csharp public class Program{ public static void Main(string[] args){ Random rand = new Random(); int success = 0; while(true){ int number = rand.Next(0,5); bool replay = false; Console.Write("我想好了一个0-5内的数字,你猜是多少?输入你的猜测或输入q退出: "); while(true){ string val = Console.ReadLine(); if(val=="q"){ break; } int a = Convert.ToInt32(val); if(a==number){ success +=1; Console.WriteLine("恭喜你才对了,是否再来一个?[y/n]:"); string ret = Console.ReadLine(); replay = ret=="y"; break; }else{ Console.WriteLine("猜错了,再来一次或输入q退出:"); } } if(!replay){ break; } } Console.WriteLine("太棒了,你一共猜对了{0}次!", success); } } ``` ## 选项 ### A ```csharp public class Program{ public static void Main(string[] args){ Random rand = new Random(0,5); int success = 0; while(true){ int number = rand.Next(); bool replay = false; Console.Write("我想好了一个0-5内的数字,你猜是多少?输入你的猜测或输入q退出: "); while(true){ string val = Console.ReadLine(); if(val=="q"){ break; } int a = Convert.ToInt32(val); if(a==number){ success +=1; Console.WriteLine("恭喜你才对了,是否再来一个?[y/n]:"); string ret = Console.ReadLine(); replay = ret=="y"; break; }else{ Console.WriteLine("猜错了,再来一次或输入q退出:"); } } if(!replay){ break; } } Console.WriteLine("太棒了,你一共猜对了{0}次!", success); } } ``` ### B ```csharp public class Program{ public static void Main(string[] args){ Random rand = new Random(); int success = 0; while(true){ int number = rand.Next(0,5); bool replay = false; Console.Write("我想好了一个0-5内的数字,你猜是多少?输入你的猜测或输入q退出: "); while(true){ string val = Console.Read(); if(val=="q"){ break; } int a = Convert.ToInt32(val); if(a==number){ success +=1; Console.WriteLine("恭喜你才对了,是否再来一个?[y/n]:"); string ret = Console.Read(); replay = ret=="y"; break; }else{ Console.WriteLine("猜错了,再来一次或输入q退出:"); } } if(!replay){ break; } } Console.WriteLine("太棒了,你一共猜对了{0}次!", success); } } ``` ### C ```csharp public class Program{ public static void Main(string[] args){ Random rand = new Random(); int success = 0; while(true){ int number = rand.Next(0,5); bool replay = false; Console.Write("我想好了一个0-5内的数字,你猜是多少?输入你的猜测或输入q退出: "); while(true){ var val = Console.ReadLine(); if(val=="q"){ break; } if(val==number){ success +=1; Console.WriteLine("恭喜你才对了,是否再来一个?[y/n]:"); string ret = Console.ReadLine(); replay = ret=="y"; break; }else{ Console.WriteLine("猜错了,再来一次或输入q退出:"); } } if(!replay){ break; } } Console.WriteLine("太棒了,你一共猜对了{0}次!", success); } } ```