Right now i have "int score" all over the place in the main() function and the subroutine functions, from trying to make the point system work if the user got the math problem right. All it does is print 1 every time currently and I cant figure out how to actually add up the points.
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <iomanip>
#include <string>
usingnamespace std;
int menu();
int addition();
int subtraction();
int main()
{
int score;
int choice;
do
{
choice = menu();
switch (choice){
case 0: cout << score; break;
case 1: addition(); break;
case 2: subtraction(); break;
default : cout << "Error in input\n\n"; break;
}
}
while (choice != 0);
}
int menu() //main menu that gets called by the switch
{
int MenuChoice;
cout << "\n";
cout << "Enter 1 for addition\n";
cout << "Enter 2 for Subtraction\n";
cout << "Enter 0 to quit\n";
cout << "-----------------\n";
cout << "Choice: ";
cin >> MenuChoice; // user input
return MenuChoice; //return the choice to choice to select a case
}
int addition() //function that is called by the users selection
{
int score=0;
int answer;
int random1, random2;
srand(time(NULL));
random1 = 1+(rand()%99); // from 1-99
random2 = 1+(rand()%99); // from 1-99
cout << "\n" << random1 << " + " << random2 << " = "; //code to format the random math problem
cin >> answer; // user input of answer
{
if (answer == (random1+random2)){
cout << "Congratulations\n\n";
++score;
cout << "\n" << score;} //if user is correct than the score is incremented
else{
cout << "Incorrect\n\n";} //if not than the score is not incremented
return score;
}
}
int subtraction() // follows same model as previous function, but instead subtraction.
{
int answer;
int random1, random2;
int score=0;
srand(time(NULL));
random1 = 1+(rand()%99); // from 1-99
random2 = 1+(rand()%99); // from 1-99
cout << "\n" << random1 << " - " << random2 << " = ";
cin >> answer;
if (answer == (random1-random2)){
cout << "Congratulations\n\n";
++score;
cout << "\n" << score;}
else{
cout << "Incorrect\n\n";}
return score;
}
well yes, but how do i apply that code into my main menu loop and functions. I kind of have what you are saying in my addition and subtraction functions already, where i increment the score ++score and print it if you are correct. But it wont save the value at all, just prints 1.
The functions addition() and subtraction() have their own local variable "score" that gets destroyed when the functions finish. Everytime main() calls either one of them, their local "score" is set to zero, incremented to 1 if applicable, that value is returned to main(), and the local variable "score" is lost (out of scope) . If main() happens to call either function again, the local variables are used, incremented to 1 if applicable, value returned to main(), then forgotten once again.
There are a few ways to correct this: one is to use a global variable, or you could pass main()'s "score" to the functions.