我已经坚持这段代码几个小时了。我是 C# 的新手并且仍在学习中所以如果你能解决我将不胜感激

I have been stuck on this code for a few hours now. I am new to C# and am still in the process of learning so i'd appreciate it if you could solv

我要编写的程序是随机生成5道数学题,最后输出分数。我知道这可能看起来很简单,但我尝试了很多不同的方法来做到这一点,但它给了我同样的问题和重复的答案,但它确实告诉我它是否正确,所以循环几乎可以正常工作。

using System;

namespace Homework
{
    class Program
    {
        static void Main(string[] args)
        {
            // Maths test problem

            string name;
            int score, ans, question1;

            Console.Write("Enter your name: ");
            name = Console.ReadLine();

            score = 0;


            Random rnd = new Random();
            int num1 = rnd.Next(10, 51);
            int num2 = rnd.Next(10, 51);

            int[] numbers = new int[2];
            numbers[0] = num1;
            numbers[1] = num2;

            Console.Write(num1 + "+" + num2 + "= ");
            question1 = Convert.ToInt32(Console.ReadLine());
            ans = num1 + num2;

            for (int i = 0; i < 5; i++)
            {
                Console.Write(question1);
                while (question1 == ans)
                {
                    Console.WriteLine("Correct");
                    score = score + 1;
                    Console.Write(question1);
                    break;
                }
                while (question1 != ans)
                {
                    Console.WriteLine("Not quite. The answer was " + ans);
                    Console.Write(question1);
                    break;
                }
            }
            Console.WriteLine("That's the end of the test. You scored " + score);



        }
    }
}

您可能需要考虑重构事物,以便单独的函数询问单个问题。

这样的事情会让用户一次性回答每个问题;您的原始代码不清楚您是否希望他们进行多次尝试。 (但是,很容易将尝试循环添加到 TestQuestion...)

using System;

namespace Homework
{
    class Program
    {
        static bool TestQuestion()
        {
            Random rnd = new Random();
            int num1 = rnd.Next(10, 51);
            int num2 = rnd.Next(10, 51);
            Console.Write(num1 + "+" + num2 + "= ");
            var userAnswer = Convert.ToInt32(Console.ReadLine());
            var correctAnswer = num1 + num2;
            if (userAnswer == correctAnswer)
            {
                Console.WriteLine("Correct");
                return true;
            }
            Console.WriteLine("Not quite. The answer was " + correctAnswer);
            return false;
        }
        static void Main(string[] args)
        {
            Console.Write("Enter your name: ");
            string name = Console.ReadLine();
            int score = 0;
            for (int i = 0; i < 5; i++)
            {
                if (TestQuestion())  // Returns true if user was correct
                {
                    score++;
                }
            }
            Console.WriteLine("That's the end of the test. You scored " + score);
        }
    }
}