1

So my lab is supposed to ask you how many questions you want and then give you that many randomly generated math problems. At the end it should ask you if you want to have another set of questions or just end and you have the option to answer y or n. when i stop the code there everything works fine but I also need to get the total amount correct printed and when I add that code I get the Unhandled Exception. My problems come from the last three lines before the brackets:

    using System;

class MainClass {
  public static void Main (string[] args) {
    var rnd = new Random();
    string exit = "";
    double score = 0;
    double total = 0; 
    double percent = 0;
    Console.WriteLine("How many problems do you want in a set?");
    double problem = Convert.ToDouble(Console.ReadLine());
    do{
    for(double i = 1; i<=problem; i++){
      double num1 = rnd.Next(1,9);
      double num2 = rnd.Next(1,9);

      Console.Write("Problem {0} : {1}*{2}=? ", i, num1, num2);
      double answer = Convert.ToDouble(Console.ReadLine());

      if(num1*num2 == answer){
        score++;
      }//end if

      total++;
      }
      Console.Write("Another set? <y/n>");
      exit = Console.ReadLine();
      Console.ReadLine();
    }while(exit!="n");
      percent = score/total;
      Console.WriteLine(" {} correct out of {} is a {}%",score,total,percent);
      Console.WriteLine("done");
  }//end main
}//end class
louisetmr
  • 43
  • 5
  • 1
    Here are some more tests for you. When this line executes: `double problem = Convert.ToDouble(Console.ReadLine());`, enter _"Ten"_. In general, you should expect that users will not follow instructions as you'd like them to. As a result: `Convert.ToDouble` or `double.Parse` are poor choices for parsing user input (and similar functions for `int`s, etc.). Read up on `double.TryParse` (and `int.TryParse`, etc.). You might also consider putting your prompting in a separate function. What happens when you ask "Another set?" and someone answers "No" (or even "N")? – Flydog57 Jan 16 '21 at 01:32
  • Does this answer your question? [Input string was not in a correct format](https://stackoverflow.com/questions/8321514/input-string-was-not-in-a-correct-format) – Progman Jan 16 '21 at 09:26

2 Answers2

1

Either number the parameters {0}, {1}, {2}, or you can now use string interpolation as follows:

Console.WriteLine($"{score} correct out of {total} is a {percent}%");
Neil W
  • 7,670
  • 3
  • 28
  • 41
1
      Console.WriteLine(" {} correct out of {} is a {}%",score,total,percent);

needed 0, 1, and 2

louisetmr
  • 43
  • 5