1

This is my code, I am a beginner to C# but used to use python, my problem is that when the user enters their answer the variable answer adds what the user entered onto 48. I have no idea where the data 48 comes from but if the user enters 2 then it will make answer = 50.

Random numGen = new Random(); //importing random
int score = 0; //setting a variable

for (int i = 0; i < 10; i++)  //for loop repeating 10 times
{ 
    int num1 = numGen.Next(1, 11); // random number between 1 and 10
    int num2 = numGen.Next(1, 11);
    Console.WriteLine("What is " + num1 + " mutliplied by " + num2 + "? "); 
    //asking a multiplication question
    int answer = 0;
    answer = Console.Read(); //input answer
    int result = num1 * num2; 
    if (result == answer) //checking answer is correct
    {
        Console.WriteLine("Well done that is correct!");
        score = score + 1;
    }
    else 
    {
        Console.WriteLine("Unlucky that was incorrect");
    }
    Console.WriteLine("Press enter for the next question");
    Console.ReadKey();  //waits before closing
}
Paul
  • 4,160
  • 3
  • 30
  • 56
hatake
  • 21
  • 3

3 Answers3

2

answer = Console.Read(); reads a character. The character is represented by an ascii number.

Since 48 = '0' - 50 = '2' and so forth, the value seems correct.

You need to use: Int32.Parse(Console.ReadLine()); to get the expected output.

Better yet use the Int32.TryParse flavor to make sure you won't get a runtime exception if the user enters a non numeric input.

int answer = 0;
Int32.TryParse(Console.ReadLine(), out answer);
Athanasios Kataras
  • 25,191
  • 4
  • 32
  • 61
1

According to the documentation, Console.Read only returns the character, not the number. You should consider using Console.ReadLine and int.TryParse instead.

misticos
  • 718
  • 5
  • 22
1

change this line :

answer = Console.Read(); //input answer

to this one :

int.TryParse(Console.ReadLine(),out answer)
Amirhossein Yari
  • 2,054
  • 3
  • 26
  • 38