提问者:小点点

用户有5个的控制台应用程序尝试猜测1到100之间的数字


我创建了一个控制台应用程序,其中用户有5次尝试猜测1到100之间的数字。猜了5次游戏就结束了,但是我不知道如何在第5次引入错误的意图像你已经达到了最大限度的猜!答案是数字(X)。我试过不同的方法,但都不奏效。这是我的程序

using System;

namespace Guessing_Game_4
{
    class Program
    {
        static void Main(string[] args)
        {
            var number = new Random().Next(1, 100);
            Console.WriteLine("Try and guess any number between 1-100. You have 5 guesses Max!");

            for (var i = 0; i < 5; i++)
            {
                int guess = Convert.ToInt32(Console.ReadLine());               
                if (guess == number)
                {
                    Console.WriteLine("You got it!");
                    break;
                }
                else
                {
                    Console.WriteLine(guess + " is not correct! Try again!");
                }   
            }
        }
    }
}

共2个答案

匿名用户

这里的一些示例代码可能会有所帮助

        for( i=10;i>0 ; i--) {
        System.out.println("    === you have " + i +" Guesses left ===");

        int guess = scanner.nextInt();
        if (random_number < guess) System.out.println("Smaller than guess  " + guess);
        if (random_number > guess) System.out.println("Greater  than guess " + guess);
        if (random_number == guess)
        {
            result = true;
            break;
        }
    }
    if (result)
    {
        System.out.println("You WON in "+(10-i) +" tries ");
        System.out.println("******* CONGRATULATIONS **************************************");
        System.out.println("*********************** YOU WON **********************");
    }
    else
    {
        System.out.println("The random number was   "+random_number);
        System.out.println("**************************  OPPS You loose **************************************** ");
        System.out.println("You are near it TRY Next time ************ GOOD LUCK ");
        System.out.println("You are near it TRY Nexttime***********NEXTTIME********");
    }
}

匿名用户

如果这就是您的程序所做的全部工作,那么您可以执行以下技巧。在for循环之后打印您的消息,但现在的问题是您在所有情况下都得到消息。诀窍是根据正确的猜测从(而不是:

Console.WriteLine("You got it!");
return;

如果您还有其他代码要执行,那么从返回并不是一个好的解决方案,您可以执行以下操作:

> ,并在开始时将其设置为false。

在他正确回答的地方,在设置为

在循环之后,检查该变量:

if (!isCorrectAnswer)
{
    Console.WriteLine($"you have achieved maximum of guesses! The answer was number {number}.");
}