我在C#(控制台应用程序)中创建了一个程序,它提示用户输入“2 + 2 =?”的答案,如果右边有一条消息弹出“完成”,如果没有则“请再试一次”。我想要做的是让程序告诉用户在得到正确答案之前他们做了多少次猜测/尝试。
这是我到目前为止所做的事情
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();
}
}
如果有人能告诉我如何使反制品工作,那就太棒了。
答案 0 :(得分:2)
你总是在循环开始时将counter
设置为1,然后立即counterUpdated = counter++;
(这有点奇怪......)。
只需使用一个在循环外初始化并在循环内递增的计数器。
int guessNumber = 0;
do {
guessNumber++;
// ...
答案 1 :(得分:1)
稍微调整一下,这应该有效:)
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
变量执行所有计数工作:)
希望它有所帮助:)