我有一个使用 C# 在线编译器的奇怪场景:
I have a weird scenario using a C# online compiler with this code:
int randomNumber;
int guess;
int countGuess;
bool correctGuess = false;
bool alreadyCalled = false;
int lastGuess;
public void Main()
{
if(!alreadyCalled)
{
RandomNumberGenerator();
alreadyCalled = true;
}
GuessWhatNumber();
}
private void GuessWhatNumber()
{
while(!correctGuess)
{
Console.WriteLine("Guess the number : ");
guess = Convert.ToInt32(Console.ReadLine());
if(guess > randomNumber)
{
Console.WriteLine("Too High");
correctGuess = false;
}
else if(guess < randomNumber)
{
Console.WriteLine("Too Small");
correctGuess = false;
}
else
{
Console.WriteLine("Correct!");
correctGuess = true;
countGuess = 0;
Environment.Exit(0);
}
if(lastGuess != guess)
{
countGuess+=1;
Console.WriteLine("Count of Guess : " + countGuess);
}
else
{
Console.WriteLine("Count of Guess is Still: " + countGuess);
}
lastGuess = guess;
}
}
private void RandomNumberGenerator()
{
Random rand = new Random();
randomNumber = rand.Next(50);
Console.WriteLine("Number To Guess : " + randomNumber);
}
Random Number Generator
方法只能调用一次,但在该在线编译器上,它会不断地调用该方法,然后再一次调用该方法.我在这里做错了什么?还是编译器?
The Random Number Generator
method must be called only once but on that online compiler it keeps calling and calling the method all over again. What am I doing wrong here? Or is it the compiler?
Dotnetfiddle.net 设置为:
运行代码后,它会作为请求发送到服务器,并将结果作为文本返回并显示在界面中.一旦遇到需要用户输入而不是等待输入的点,就会再次发送完整的请求,但这次是来自输入窗口的信息.然后在后端,完整的请求再次运行,并自动添加已知用户的输入.
Once you run the code it is send to the server as request and it'll return the results as text to display in the interface. Once it encounters a point where it requires the users input instead of waiting for the input the full request is send again, but this time with the information from the input window. Then on the backend the full request runs again and automatically adds the input from the users as far as it's known.
在大多数情况下,这不会有问题,因为相同的脚本通常会产生相同的结果.但是,这是一种不同的情况,因为您在脚本中添加了一个随机元素.因此,每次输入新数据时,之前发生的一切都会再次运行,并可能产生不同的结果.
In most cases that would be no problem because the same script usually yields the same results. This is a different case however because you added a random element into the script. So each time you input new data everything that happened before runs again and may yield different results.
这篇关于DotNetFiddle 和 Console.ReadLine 出现问题,在按下 ENTER 键时会导致重新运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!