C++

Javier R.

asked • 02/25/21

C++ program -Math Tutor

I have a HW assignment that is to make a program that will allow a user to select either to add or subtract a random number from 1-500. The user types in their answer and if correct they will receive a congratulations messaged on screen. If incorrect they will receive a message stating "incorrect the correct answer is:". I have written the code and it works but on the subtract function when I test it and get the question wrong on purpose it gives me a message saying the correct answer is and instead of subtracting the numbers properly it adds them. I have tried everything to fix it but no luck. Does anyone know what could be wrong? That is the only thing not working.



#include <iostream>

#include <ctime>

#include <cstdlib>

using namespace std;


int main()

{

//1. Variables

srand(time(0));

int num1 = rand() % 500 + 1;

int num2 = rand() % 500 + 1;

int answer = 0;

int answer2 = 0;

int correctanswer = num1 + num2;

int correctanswer2 = num1 - num2;

int choice = 0;


//2. Talk to the user/Decision

cout << "Would you like to ADD(1) or SUBTRACT(2)?" << endl;

cin >> choice;

if (choice == 1)

{

cout << "Please Answer The Following:" << endl;

cout << num1 << "+" << num2 << "=";

cin >> answer;

}

else if (choice == 2)

{

cout << "Please Answer The Following:" << endl;

cout << num1 << "-" << num2 << "=";

cin >> answer2;

}

//3. Store the variables

if (answer == num1 + num2)

{

cout << "Congratulations! You are correct!" << endl;

}

else if (answer2 == num1 - num2)

{

cout << "Congratulations! You are correct!" << endl;

}

else if (answer != num1 + num2)

{

cout << "Incorrect, the correct answer is:" << endl;

cout << correctanswer;

}

else if (answer2 != num1 - num2)

{

cout << "Incorrect, the correct answer is:" << endl;

cout << correctanswer2;

}

}

1 Expert Answer

By:

Patrick B. answered • 02/25/21

Tutor
4.7 (31)

Math and computer tutor/teacher

Still looking for help? Get the right answer, fast.

Ask a question for free

Get a free answer to a quick problem.
Most questions answered within 4 hours.

OR

Find an Online Tutor Now

Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.