做...虽然循环计数器实现不起作用

Do... While loop counter implementation not working

我在 C#(控制台应用程序)中创建了一个程序,提示用户输入“2+2=?”的答案,如果正确则弹出消息 "Well done",如果不正确则 "Please try again"。我想要做的是让程序告诉用户在得到正确答案之前他们已经做了多少guesses/attempts。

这是我目前所做的

class Program
{
    public static int correct_answer, counter,  user_answer, counterUpdated;

    static void Main(string[] args)
    {
        correct_answer = 4;

        do 
        {
            counter = 1;
            counterUpdated = counter++;

            Console.WriteLine("2+2= ?");
            user_answer = Convert.ToInt32(Console.ReadLine());

            if (user_answer != correct_answer)
            {
                Console.Clear();
                Console.WriteLine("Wrong, try againg" + " this is your " + counterUpdated + " try.");
            }
        } while (user_answer != correct_answer); // The code will keep looping until the user prompts the correct answer 

        Console.Clear();
        Console.WriteLine("Well Done! you did it in this amount of guesses " + counterUpdated);
        Console.ReadLine();
    }
}

如果有人能告诉我如何使计数器工作,那就太好了。

您总是在循环开始时将 counter 设置为 1,然后立即设置 counterUpdated = counter++;(无论如何这有点奇怪...)。 只需使用一个在循环外初始化并在循环内递增的计数器即可。

int guessNumber = 0;
do {
    guessNumber++;
    // ...

稍微调整了一下,应该可以了:)

class Program
{
    public static int correct_answer, counter,  user_answer;

    static void Main(string[] args)
    {
        correct_answer = 4;
        counter = 0;
        do 
        {

            counter++;

            Console.WriteLine("2+2= ?");
            user_answer = Convert.ToInt32(Console.ReadLine());

            if (user_answer != correct_answer)
            {

                Console.Clear();
                Console.WriteLine("Wrong, try againg" + " this is your " + counter+ " try.");

            }



        } while (user_answer != correct_answer); // The code will keep looping until the user prompts the correct answer 
        Console.Clear();
        Console.WriteLine("Well Done! you did it in this amount of guesses " + counter);
        Console.ReadLine();



    }
}

我所做的是删除 counterUpdated 变量并让 counter 变量完成所有计数工作:)

希望对您有所帮助:)