C# 如何将Console.ReadLine循环到无穷大?
您好,我正在尝试创建一个计算器游戏,但它只循环2次(idk why),直到用户通过输入找到结果。稍后我将看到如何生成一个随机数字生成器,而不是自己在代码中编写它们。谢谢你的帮助 亚辛C# 如何将Console.ReadLine循环到无穷大?,c#,loops,math,calculator,infinite,C#,Loops,Math,Calculator,Infinite,您好,我正在尝试创建一个计算器游戏,但它只循环2次(idk why),直到用户通过输入找到结果。稍后我将看到如何生成一个随机数字生成器,而不是自己在代码中编写它们。谢谢你的帮助 亚辛 using System; namespace G { class Program { static void Main(string[] args) { Calcul(2, 2); } static voi
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
。完美的循环条件
然后,您可以将“success”消息放在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();
}
“它只循环2次”-不,它不。。。你知道如何使用实际循环吗?(我尝试了while循环,但没有找到如何处理它。)你在
while
循环中遇到了什么问题?它们是非常基本的特性。也许可以从一个简单的教程开始,比如?while(true){//put code-inside-loop here}
Duplicate of、、和其他许多教程。