mercredi 7 octobre 2015

"If" part not executing (C#)

As a part of my programming class, I'm fairly new to it so I need some help.

I have to create a program that does the following (loosely translated) :

  1. Create a program that will let a child practice his mathematics;

  2. Make him type in a number, an arithmetic operator, another number and finally, the answer to the equation;

  3. If the answer to said equation is correct, display a message saying "Bravo";

  4. If the answer is NOT correct. make him type in another answer. He has a maximum of 8 chances (including the first one); and

  5. If after 8 tries he still doesn't get the answer to his own equation, you can tell him to go take a break.

The problem that I have in my code is that one of the last conditions ( if (ans == nb3)) never executes even.

For example, I'd type in 1 - 1 = 5. It would say that my answer is false and that I need to type another answer, to this point, everything is fine. If I were to type in the right answer after that ( 1 - 1 = 0 ), it would still ask me to type in another answer instead of breaking the loop.

The current state of my program:

        int nb1, nb2, nb3, ans = 0;
        string op;
        Console.WriteLine("Entrez un premier chiffre");
        nb1 = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("Entrez un operateur arithmetique ");
        op = Convert.ToString(Console.ReadLine());
        Console.WriteLine("Entrez un deuxieme chiffre");
        nb2 = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("Quel est la reponse");
        nb3 = Convert.ToInt32(Console.ReadLine());


        switch (op)
        {

            case ("+"):
            case ("plus"):
                ans = nb1 + nb2;
                break;

            case ("-"):
            case ("moins"):
                ans = nb1 - nb2;
                break;

            case ("*"):
            case ("multiplie"):
                ans = nb1 * nb2;
                break;

            case ("/"):
            case ("divise"):
                ans = nb1 / nb2;
                break;
        }

        if (ans == nb3)
            Console.WriteLine("Bravo");

        else
        {
            Console.WriteLine("Mauvaise reponse");
            for (int t = 1; t < 8; t++)
            {

                Console.WriteLine("Quel est la reponse?");
                Console.ReadLine();
                    if (ans == nb3)
                    {
                        break;
                    }

               }
            }

        }
    }

}     

Aucun commentaire:

Enregistrer un commentaire