我是 C# 新手,在循环方面遇到了一些困难。 对于这个,我尝试使用“for”循环。我尝试了各种选项 - for、while 循环,但我无法达到预期的结果。
对于这个,即使我“猜”到了数字,他们也说我输了。
{
var random = new Random();
int random2 = Convert.ToInt32(random.Next(0, 10));
Console.WriteLine(random2);
for (var i = 4; i <= 4; i++)
{
Console.WriteLine("Please enter a number from 0 to 10:");
var input = Convert.ToInt32(Console.ReadLine());
if (input != random2)
{
Console.WriteLine("You have {0} tries left.", i - 1);
continue;
}
if (input != random2)
{
Console.WriteLine("You have {0} tries left.", i - 1);
continue;
}
if (input != random2)
{
Console.WriteLine("You have only {0} try left!!", i - 1);
continue;
}
if (input == random2)
{
Console.WriteLine("You lose!!!");
break;
}
if (input == random2)
{
Console.WriteLine("You have won!!!!!");
break;
}
}
}
我想做的事:编写一个程序,选择 1 到 10 之间的随机数,并为用户提供 4 次猜测的机会。但是,我想让控制台打印剩余的尝试次数,并在用户最后一次尝试时打印不同的消息。
让我们从头开始一步步实现吧:
attempt
而不是i
)// Computer pick the number in 1..9 range
int picked = Random.Shared.Next(1, 10);
// We have 4 attempts
int attempts = 4;
// We haven't found the picked number yet
bool found = false;
// for each attempt
for (int attempt = 1; attempt <= attempts; ++attempt) {
// We are asked to guess
Console.WriteLine("Please enter a number in 1 .. 9 range:");
// We do our guess - note, int.TryParse is a better option
int guess = int.Parse(Console.ReadLine());
// If we guess right then ...
if (guess == picked) {
// ... the picked number is found and
found = true;
// we don't want any attempt more
break;
}
// if we don't guess right, show number of attempts
Console.WriteLine($"You have {attempts - attempt + 1} tries left.");
}
// after all attempts show outcome
if (found)
Console.WriteLine("You have won!!!!!");
else
Console.WriteLine("You have lost.");