[英]Random Number generator fail
如果选择了错误的编号,如何使程序从头开始循环播放? 我不确定自己在做什么错。 我想if
S, do while
S, while
S,以及if else
S:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ArrayProblms
{
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Guess a number between 1 and 10: ");
RandomNumberGenerator();
Console.ReadLine();
}
public static void RandomNumberGenerator()
{
Random rand = new Random();
int userValue = int.Parse(Console.ReadLine());
int randValue = rand.Next(1, 11);
int attempts = 0;
if (userValue == randValue)
{
Console.WriteLine("You have guessed correctly!");
}
while (userValue != randValue)
{
Console.WriteLine("You have guessed incorrectly");
attempts++;
Console.WriteLine("You have made {0} incorrect guesses", attempts);
break;
}
}
}
}
您应该将int userValue = int.Parse(Console.ReadLine());
在循环中检查每次迭代的输入。 break
必须是只有userValue == randValue
:
public static void RandomNumberGenerator()
{
Random rand = new Random();
int randValue = rand.Next(1, 11);
int attempts = 0;
while (true)
{
int userValue = int.Parse(Console.ReadLine()); // input inside the loop
if (userValue == randValue) // checking inside the loop
{
Console.WriteLine("You have guessed correctly!");
break;
}
Console.WriteLine("You have guessed incorrectly");
attempts++;
Console.WriteLine("You have made {0} incorrect guesses", attempts);
}
}
你在正确的轨道上,但是你需要把Console.ReadLine
while循环中,并break
循环,只有当用户的值匹配的了。
像这样的伪代码:
Generate random number
while (true) {
Get value from user
If it matches, break
}
do...while
继续要求用户输入新号码之前,我会使用do...while
直到他猜对为止。
下面的例子:
public static void RandomNumberGenerator()
{
Random rand = new Random();
int randValue = rand.Next(1, 11);
int attempts = 0;
// do...while cycle to ask user to enter new value each time the used has been wrong
do
{
// read user input
int userValue = int.Parse(Console.ReadLine());
// if user guessed correct
if (userValue == randValue)
{
Console.WriteLine("You have guessed correctly!");
// go away from do...while loop
// it will stop asking user and will exit from the method
break;
}
// if user has been wrong
Console.WriteLine("You have guessed incorrectly");
// increment attempts count
attempts++;
Console.WriteLine("You have made {0} incorrect guesses", attempts);
}
// and repeat until user guessed correctly
while(userValue != randValue)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.