Если циклы / else: C ++ Программа: Не отображать окончательный запрос / последний цикл - PullRequest
0 голосов
/ 25 мая 2018

У меня много проблем с этим заданием для моего первого курса C ++.

Я выяснил, как заставить его правильно спросить пользователя, какую операцию он хотел бы использовать (сложение, вычитание, умножить), генерировать случайные числа в диапазоне от 0 до 9 и узнать, как попросить пользователя решить проблему и ответить, если она правильная или неправильная.

После этого момента программа должна спросить пользователя, хочет ли он продолжить (нажав y) или выйти (нажав Q), с сообщением об ошибке для пользователя при вводе любой другой буквы., но по какой-то причине эта часть не отображается при запуске программы.

Как мне заставить цикл работать правильно, позволяя мне сделать последнее приглашение, а затем повторить всю программу только при нажатии Yили выйти при нажатии Q?

Примечание: я ОЧЕНЬ новичок в программировании в целом, и это мой самый первый курс C ++, поэтому я пока не знаю, как создать этот кодболее кратко:

#include <iostream>
#include <cstdio>
#include <time.h>
#include <stdlib.h>
using namespace std;

int main()

{
    while (true)
   {
  // Generate two random single-digit integers btwn 0-9
  srand(time(0));
  int num1 = rand() % 10;
  int num2 = rand() % 10;
  int operation, play, num3, guess, Y, Q;

  // If num1 < num2, swap num1 with num2
  if (num1 < num2)
  {
  int temp = num1;
  num1 = num2;
  num2 = temp;
  }

cout << "Choose an operation." << endl;
cout << "Enter 1 to add, 2 to subtract, or 3 to multiply: " << endl;
cin >> operation;

    if (operation > 3 || operation < 1)
    {
        cout << "Your operation choice isn't valid!  Please try again, using 1, 2, or 3." << endl;
        cout << "Choose an operation." << endl;
        cout << "Enter 1 to add, 2 to subtract, or 3 to multiply: " << endl;
        cin >> operation;
    }

     else if (operation == 1)
        {
        cout << "You chose addition." << endl;
        num3 = num1 + num2;
        cout << "What is " <<  num1 << " + " << num2 << " ?: " << endl;
        cin >> guess;

            if (guess != num3)
                {
                cout << "That is incorrect. Please try again." << endl;
                cout << "" << endl;
                cout << "What is " <<  num1 << " + " << num2 << " ?: " << endl;
                cin >> guess;
                }

            else if (guess == num3)
                {
                cout << "That is correct!" << endl;
                cout << "" << endl;
                }
        }

     else if (operation == 2)
        {
        cout << "You chose subtraction." << endl;
        num3 = num1 + num2;
        cout << "What is " <<  num1 << " - " << num2 << " ?: " << endl;
        cin >> guess;

            if (guess != num3)
                {
                cout << "That is incorrect. Please try again." << endl;
                cout << "" << endl;
                cout << "What is " <<  num1 << " - " << num2 << " ?: " << endl;
                cin >> guess;
                }

            else if (guess == num3)
                {
                cout << "That is correct!" << endl;
                cout << "" << endl;
                }
        }

     else if (operation == 3)
        {
        cout << "You chose multiplication." << endl;
        num3 = num1 * num2;
        cout << "What is " <<  num1 << " * " << num2 << " ?: " << endl;
        cin >> guess;

            if (guess != num3)
                {
                cout << "That is incorrect. Please try again." << endl;
                cout << "" << endl;
                cout << "What is " <<  num1 << " * " << num2 << " ?: " << endl;
                cin >> guess;
                }

            else if (guess == num3)
                {
                cout << "That is correct!" << endl;
                cout << "" << endl;
                }
        }

while (guess != num3)
         {
         int play, Y, Q;
         cout << "Would you like to play again? Press Y for yes or Q for 
quit" << endl;
         cin >> play;

           if (play != Y || play != Q)
            {
                cout << "That is not a valid choice. Please choose Y for yes 
or Q to quit. " << endl;
                cin >> play;
            }

            else
            {
                if (play == Y)
                {
                cout << "Thank you for playing! Let's play again!" << endl;
                cout << "" << endl;
                }


                else if (play == Q)
                {
                cout << "Thank you for playing! See you next time!" << endl;
                cout << "" << endl;
                }
                break;
                }
         }
         }
return 0;
}

Ответы [ 4 ]

0 голосов
/ 26 мая 2018

Решение:

P29: Практика арифметических навыков (если / еще, цикл)

Описание:

"Напишите программу, чтобы позволить ребенку практиковать арифметикунавыки.

Программа должна сначала спросить, какой вид практики требуется: +, -, *, и позволить пользователю повторять практику столько раз, сколько необходимо, пока не будет введено «Q».

Из (0 - 9) будут сгенерированы два случайных числа.

Если ребенок правильно ответит на уравнение, должно появиться сообщение, и они могут перейти к следующей задаче (сгенерировано два разных числа).

Если ребенок ответит неправильно, должно появиться сообщение и проблема должна быть повторена (используются те же цифры). "

Окончательно исправлено! :

    #include <iostream>
    #include <cstdio>
    #include <time.h>
    #include <stdlib.h>
    using namespace std;

    int main()
   {
    int operation, num3, guess, num1, num2, temp;
    char play;
    srand(time(0));

    do
    {
      num1 = rand() % 10;
      num2 = rand() % 10;

      if (num1 < num2)
      {
          temp = num1;
          num1 = num2;
          num2 = temp;
      }

        do
        {
            cout << "Choose an operation." << endl;
            cout << "Enter 1 to add, 2 to subtract, or 3 to multiply: " << endl;
            cout << "" << endl;
            cin >> operation;

            if (operation > 3 || operation < 1)
            {
                cout << "Your operation choice isn't valid!  Please try again, using 1, 2, or 3." << endl;
            }
        }while (operation > 3 || operation < 1);

        switch(operation)
        {
            case 1:
            cout << "You chose addition." << endl;
            num3 = num1 + num2;
            cout << "" << endl;

            do
            {
                cout << "What is " <<  num1 << " + " << num2 << " ?: " << endl;
                cout << "" << endl;
                cin >> guess;
                cout << "" << endl;

                if (guess != num3)
                    {
                    cout << "That is incorrect. Please try again." << endl;
                    cout << "" << endl;
                    }
            } while (guess != num3);

                if (guess == num3)
                    {
                    cout << "That is correct!" << endl;
                    cout << "" << endl;
                    }
            break;

            case 2:
            cout << "You chose subtraction." << endl;
            num3 = num1 - num2;
            cout << "" << endl;

            do
            {
                cout << "What is " <<  num1 << " - " << num2 << " ?: " << endl;
                cout << "" << endl;
                cin >> guess;
                cout << "" << endl;

                if (guess != num3)
                    {
                    cout << "That is incorrect. Please try again." << endl;
                    cout << "" << endl;
                    }
            } while (guess != num3);

                if (guess == num3)
                    {
                    cout << "That is correct!" << endl;
                    cout << "" << endl;
                    }
            break;

            case 3:
            cout << "You chose multiplication." << endl;
            num3 = num1 * num2;
            cout << "" << endl;

            do
            {
                cout << "What is " <<  num1 << " * " << num2 << " ?: " << endl;
                cout << "" << endl;
                cin >> guess;
                cout << "" << endl;

                if (guess != num3)
                    {
                    cout << "That is incorrect. Please try again." << endl;
                    cout << "" << endl;
                    }
            } while (guess != num3);

                if (guess == num3)
                    {
                    cout << "That is correct!" << endl;
                    cout << "" << endl;
                    }
            break;
        }

        do
        {
             cout << "Would you like to play again? Press Y for yes or Q for quit" << endl;
             cout << "" << endl;
             cin >> play;

           if (play != 'Y' && play != 'Q')

            {
                cout << "That is not a valid choice. Please choose Y for yes or Q to quit. " << endl;
                cout << "" << endl;
            }

        }

        while(play !='Y' && play !='Q');

        if (play == 'Y')
        {
        cout << "Thank you for playing! Let's play again!" << endl;
        cout << "" << endl;
        }

        else
        {
        cout << "Thank you for playing! See you next time!" << endl;
        cout << "" << endl;
        }

     }
     while(play=='Y');

    return 0;
    }
0 голосов
/ 25 мая 2018

Может быть лучше использовать регистр переключателя для выбора правильной операции, например, такой:

Switch(operation) {case 1: break;}

Вам нужно добавить еще одну, пока слишком ТАК, правильный код должен выглядеть следующим образом:

#include <iostream>
#include <cstdio>
#include <time.h>
#include <stdlib.h>
using namespace std;

int main()

{
        int operation, num3, guess,num1,num2,temp;
        srand(time(0));
        char play;
        do
        {
        // Generate two random single-digit integers btwn 0-9
          num1 = rand() % 10;
          num2 = rand() % 10;

          // If num1 < num2, swap num1 with num2
          if (num1 < num2)
          {
              temp = num1;
              num1 = num2;
              num2 = temp;
          }
            do
            {
                cout << "Choose an operation." << endl;
                cout << "Enter 1 to add, 2 to subtract, or 3 to multiply: " << endl;
                cin >> operation;

                if (operation > 3 || operation < 1)
                {
                    cout << "Your operation choice isn't valid!  Please try again, using 1, 2, or 3." << endl;
                    cout << "Choose an operation." << endl;
                    cout << "Enter 1 to add, 2 to subtract, or 3 to multiply: " << endl;
                    cin >> operation;
                }
            }while(operation>3 || operation<1);
            switch(operation)
            {
                case 1:
                cout << "You chose addition." << endl;
                num3 = num1 + num2;
                do
                {
                    cout << "What is " <<  num1 << " + " << num2 << " ?: " << endl;
                    cin >> guess;
                    if (guess != num3)
                        {
                        cout << "That is incorrect. Please try again." << endl;
                        cout << "" << endl;
                        }
                }while(guess!=num3);
                cout << "That is correct!" << endl;
                cout << "" << endl;
                break;
                case 2:
                    cout << "You chose subtraction." << endl;
                    num3 = num1 - num2;
                    do
                    {
                        cout << "What is " <<  num1 << " - " << num2 << " ?: " << endl;
                        cin >> guess;
                        if (guess != num3)
                            {
                            cout << "That is incorrect. Please try again." << endl;
                            cout << "" << endl;
                            }
                    }while(guess!=num3);
                    cout << "That is correct!" << endl;
                    cout << "" << endl;
                    break;
                case 3:
                    cout << "You chose multiplication." << endl;
                    num3 = num1 * num2;
                    do
                    {
                        cout << "What is " <<  num1 << " * " << num2 << " ?: " << endl;
                        cin >> guess;

                            if (guess != num3)
                                {
                                cout << "That is incorrect. Please try again." << endl;
                                cout << "" << endl;
                                }
                    }while(guess!=num3);
                    cout << "That is correct!" << endl;
                    cout << "" << endl;
                break;
            }
            do
            {
                 cout << "Would you like to play again? Press Y for yes or Q for quit" << endl;
                cin >> play;
               if (play != 'Y' && play != 'Q')
                {
                    cout << "That is not a valid choice. Please choose Y for yes or Q to quit. " << endl;
                }
            }while(play!='Y' && play!='Q');
            if (play == 'Y')
            {
            cout << "Thank you for playing! Let's play again!" << endl;
            cout << "" << endl;
            }
            else
            {
            cout << "Thank you for playing! See you next time!" << endl;
            cout << "" << endl;
            }
         }while(play=='Y');
return 0;
}
0 голосов
/ 25 мая 2018

Проблема обнаружена во втором while-loop.Переменная play должна быть объявлена ​​как char, а не int.Кроме того, вам не нужно сравнивать его с Y и Q целочисленными переменными.Вот решение.Надеюсь, это поможет вам:

#include <iostream>
#include <cstdio>
#include <time.h>
#include <stdlib.h>
using namespace std;

int main()
{
    bool loop = true;
    while (loop)
    {
        // Generate two random single-digit integers btwn 0-9
        srand(time(0));
        int num1 = rand() % 10;
        int num2 = rand() % 10;
        int operation, play, num3, guess, Y, Q;

        // If num1 < num2, swap num1 with num2
        if (num1 < num2)
        {
            int temp = num1;
            num1 = num2;
            num2 = temp;
        }

        cout << "Choose an operation.\n\t-----------------------" << endl;
        cout << "\tEnter 1 to add,\n\tEnter 2 to subtract, or\n\tEnter 3 to multiply\n\t-----------------------\n\t\tEnter: ";
        cin >> operation;

        if (operation > 3 || operation < 1)
        {
            cout << "Invalid choice! Please try again." << endl;
            continue;
        }
        else if (operation == 1)
        {
            cout << "You chose addition." << endl;
            num3 = num1 + num2;
            cout << "What is " <<  num1 << " + " << num2 << " = ";
            cin >> guess;
            if (guess != num3)
            {
                cout << "That is incorrect. Please try again." << endl;
                cout << "What is " <<  num1 << " + " << num2 << " = ";
                cin >> guess;
            }
            else if (guess == num3)
                cout << "That is correct!" << endl;
        }
        else if (operation == 2)
        {
            cout << "You chose subtraction." << endl;
            num3 = num1 + num2;
            cout << "What is " <<  num1 << " - " << num2 << " = ";
            cin >> guess;

            if (guess != num3)
            {
                cout << "That is incorrect. Please try again." << endl;
                cout << "What is " <<  num1 << " - " << num2 << " = ";
                cin >> guess;
            }
            else if (guess == num3)
                cout << "That is correct!" << endl;
        }
        else if (operation == 3)
        {
            cout << "You chose multiplication." << endl;
            num3 = num1 * num2;
            cout << "What is " <<  num1 << " * " << num2 << " = ";
            cin >> guess;
            if (guess != num3)
            {
                cout << "That is incorrect. Please try again." << endl;
                cout << "What is " <<  num1 << " * " << num2 << " = ";
                cin >> guess;
            }
            else if (guess == num3)
                cout << "That is correct!" << endl;
        }

        while (true)
        {
            char play;
            cout << "Would you like to play again? Press Y for yes or Q for quit: ";
            cin >> play;
            if (play == 'Y' || play == 'y')
                break;
            else if(play == 'Q' || play == 'q')
            {
                loop = false;
                cout << "Good bye.\n";
                break;
            }
            else
                cout<< "Invalid choice.\n";
        }
    }
    return 0;
}

Сделать меню немного интерактивным - это тоже хорошо, мир.

0 голосов
/ 25 мая 2018

Здесь есть несколько вещей ...

1.Засевайте только один раз

Переместите srand(time(0)); из цикла while в верхнюю часть main.Если вы повторно посеете в одну и ту же секунду (если time(0) не изменится), вы получите одинаковые «случайные» числа дважды.

2.Что случится с num3, если они не введут действительный operation?

Вы никогда не инициализируете num3, поэтому, если они не выберут действительный operation, num3 получитмусорная стоимость.Затем вы запускаете цикл, состояние которого зависит от значения num3!(while (guess != num3))

3.else { ... if { совпадает с else if {

В вашем последнем цикле извлеките if (play == Y) и else if (play == Q) из этого вложенного if и сделайте их else if.

4.Ваше последнее условие цикла неверно

Действительно ли while (guess != num3) верно?Вы хотите зацикливаться, пока они не введут действительный ввод, так почему вы зацикливаетесь, пока guess != num3?

...