如何在c#中实现until循环

问题描述 投票:0回答:3

我正在制作一个简单的“较高,较低”游戏,我希望游戏继续下去,直到猜到正确的数字或者猜测者想要重新开始。我使用什么循环以及如何实现它

我的代码是

Random RandomNumber = new Random();
int RandomNumber2 = RandomNumber.Next(1, 5);
//Console.WriteLine(RandomNumber2);

//want to insert loop here and it should end when the third else if is done

Console.WriteLine("Make Your Guess Now");
string UserInput = Console.ReadLine();
int UserInput2 = Convert.ToInt32(UserInput);

if (UserInput2 > RandomNumber2)
{
    Console.WriteLine("Your Number is to high");
}
else if (UserInput2 < RandomNumber2)
{
    Console.WriteLine("Your Number is too small");
}
else if (UserInput2 == RandomNumber2)
{
    Console.WriteLine("Congrats on guessing the right number");
}
c# loops while-loop
3个回答
1
投票

执行此操作的标准方法是使用 do while 循环(C# 参考)

但是在这里,您可以使用无限循环并使用

break
语句退出。这允许您从循环内测试的条件跳出循环

...
Console.WriteLine("Make Your Guess Now");
while (true) {
    string UserInput = Console.ReadLine();
    int UserInput2 = Convert.ToInt32(UserInput);

    if (UserInput2 > RandomNumber2)
    {
        Console.WriteLine("Your Number is too high. Make another guess");
    }
    else if (UserInput2 < RandomNumber2)
    {
        Console.WriteLine("Your Number is too small. Make another guess");
    }
    else
    {
        Console.WriteLine("Congrats on guessing the right number");
        break;
    }
}

注意,最后的else中不需要测试

UserInput2 == RandomNumber2
,因为上面已经处理了其他情况,这是剩下的唯一可能性。请注意,只有当 if 部分未执行时才会执行 else 部分。


0
投票

就像说的,我认为最好的解决方案是

Do
{
  --if here
} While (userinput2==randomnumber2)

0
投票

您还可以使用函数式方法来实现这样的游戏。使用 do-while 循环应该足够了,但是有很多方法可以解决您的问题。 C# 是面向对象编程 OOP 和函数式编程 (FP) 的混合体。

首先定义游戏状态:

public record GameState {
    public int CorrectNumber { get; set; }
    public int GuessedNumber { get; set; }  
    public int NumberOfGuesses { get; set; }
}

接下来定义一个执行“trampolining”的功能扩展方法,使用更新方法和作为 func 传入的结束条件方法进行迭代。

public static class FunctionalExtensions {
    
    public static T IterateUntil<T>(this T @this, Func<T, T> updateFunction, Func<T, bool> endCondition){
        var currentThis = @this; 
        while (!endCondition(currentThis)){
            currentThis = updateFunction(currentThis);
        }
        return currentThis;
    }
}

我们的游戏在 Main 方法中定义如下:

void Main()
{
    var randomNumber2 = new Random().Next(1,5);
    
    Func<GameState, GameState> updateFunction = gameState=> {
        Console.WriteLine("Guess the correct number!");
        Console.WriteLine("Make your guess now (1-5). Enter -1 to exit before.");
        var updatedGameState = gameState;
        if (int.TryParse(Console.ReadLine(), out int guessedNumber)){
            updatedGameState = updatedGameState with { GuessedNumber = guessedNumber, NumberOfGuesses = gameState.NumberOfGuesses + 1 };
            if (updatedGameState.GuessedNumber != -1)
            {
                Console.WriteLine($"Player guessed: {updatedGameState.GuessedNumber} ");
            }
            else {
                Console.WriteLine($"Player exited the game early");
            }
            if (updatedGameState.CorrectNumber > updatedGameState.GuessedNumber){
                Console.WriteLine("Too low. Guess higher");
            }
            else if (updatedGameState.CorrectNumber < updatedGameState.GuessedNumber) {
                Console.WriteLine("Too high. Guess lower");
            }
        }
        else  {
            Console.WriteLine("Please enter a number");
            updatedGameState = updatedGameState with { NumberOfGuesses = gameState.NumberOfGuesses + 1 };
        }       
        
        return updatedGameState;
    };
    
    Func<GameState, bool> endCondition = gameState => gameState.CorrectNumber == gameState.GuessedNumber || gameState.GuessedNumber == -1;
    
    var initialState = new GameState{ NumberOfGuesses = 0, CorrectNumber = randomNumber2 };
    
    var finalState = initialState.IterateUntil(updateFunction, endCondition);

    Console.WriteLine($"Number of guesses : {finalState.NumberOfGuesses}. Was the correct number guessed ? {(finalState.CorrectNumber == finalState.GuessedNumber ? "YES!" : "No")}");
    
}

我在 Linqpad 7 中测试了上面的代码,您可以直接将代码粘贴到那里,Linqpad 可供所有 C# 开发人员测试 C# 概念并使用代码,屏幕截图:

Guess the correct num in Linqpad 7

© www.soinside.com 2019 - 2024. All rights reserved.