Hello, I'm working on an assignment for school and was just having some trouble with it. In particular, I'm having trouble with generating a random number between 1-4, then assigning that number to a basic math operator to be used in an equation, comparing two randomly generated integers.
#include<iostream>
#include<conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
usingnamespace std;
class MathProblem
{
private:
int first;
int second;
int getOper; //integers to be used throughout
int answer;
int correct;
char oper;
public:
void showOther();
void showProblem();
void setProblem(); //declare the functions
void getAnswer();
};
void MathProblem::setProblem()
{
srand(time(0));
int num1 = rand() % 60 + 12; //generate first operand
int num2 = rand() % 10 + 1; //generate second operand
int getOper = rand() % 5 + 1; //generate operator number
first = num1;
second = num2;
char operate;
if (getOper == 1)
{
operate = '+';
}
if (getOper == 2)
{
operate = '-';
}
if (getOper == 3)
{
operate = '*';
}
if (getOper == 4)
{
operate = '/';
}
}
void MathProblem::showProblem()
{
cout << first << oper << second << " = " << endl;
if (getOper == 1) //for +
{
correct = first + second;
}
if (getOper == 2) //for -
{
correct = first - second;
}
if (getOper == 3) //for *
{
correct = first * second;
}
if (getOper == 4) //for /
{
correct = first / second;
}
}
void MathProblem::getAnswer()
{
cin >> answer;
}
void MathProblem::showOther()
{
cout << "Your answer was: " << answer << endl;
cout << "The correct answer was: " << correct << endl;
cout << "Were you correct? ";
if (answer == correct)
{
cout << "1";
}
else
{
cout << "0";
}
}
int main()
{
MathProblem problem;
problem.setProblem();
problem.showProblem();
problem.getAnswer();
problem.showOther();
getch();
}
My integers are randomly generated each time, however my operator between them is null data, and my "correct answer was: " line yields something like -8980375 every time (I've fixed this error before, but I can't seem to think of what's causing it this time)
Also, any other pointers you happen to have would be greatly appreciated.
Why don't you just assign your results directly to the member variables instead of putting them in temporary then immediately assigning them somewhere else?
As for your actual problem, you are assigning your operation to a NEW, local, temporary variable that is not the same as getOper in your class. This would be easier to see if you didn't create these unnessecary temporary variables.