The program I have to create is that I need to randomly generate 5 maths questions and in the end output the score. I know this might seem simple but i have tried many different ways to do it but it gives me the same question and answer repeated but it does tell me if it it correct or not so the loop is almost working.
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);
}
}
}
CodePudding user response:
You might want to consider refactoring things so a single question is asked by a separate function.
Something like this will give the user a single shot at answering each question; your original code is not clear in whether you wanted them to have multiple tries. (However, it's easy to add an attempt loop into 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);
}
}
}