问题描述
您好,我正在尝试创建一个计算器游戏,但是它仅循环2次,(直到为什么)直到用户找到带有输入的结果。稍后,我将介绍如何制作数字的随机生成器,而不是自己在代码中编写数字。请帮忙。
Yassine
using System;
namespace G
{
class Program
{
static void Main(string[] args)
{
Calcul(2,2);
}
static void Calcul(int nombre1,int nombre2)
{
int result = nombre1 + nombre2;
Console.WriteLine("Combien font " + nombre1 + " + " + nombre2);
int supposed = int.Parse(Console.ReadLine());
if(result != supposed)
{
Console.WriteLine("Try again!");
supposed = int.Parse(Console.ReadLine());
}
else
{
Console.Clear();
Console.WriteLine("Correct!");
}
}
}
}
解决方法
您可以将if
语句更改为while
循环,其条件是输入与结果不匹配。我们还可以将int.TryParse
与Console.ReadLine
一起使用,以处理用户未输入有效数字的情况。这可以通过使用out
参数来实现,如果成功,该参数将设置为已解析的值,然后返回表示成功的bool
。完美的循环条件!
然后,您可以在while
循环的主体之后 后面添加“成功”消息(因为退出循环的唯一方法是获得正确的答案)。看起来像这样:
static void Calcul(int nombre1,int nombre2)
{
int result = nombre1 + nombre2;
int input;
Console.Write($"Combien font {nombre1} + {nombre2} = ");
while (!int.TryParse(Console.ReadLine(),out input) || input != result)
{
Console.WriteLine("Incorrect,please try again.");
Console.Write($"Combien font {nombre1} + {nombre2} = ");
}
Console.WriteLine("Correct! Press any key to exit.");
Console.ReadKey();
}