### [Problem] Avoid having negative answers for subtraction. Dear C++ community

I am currently faced with a problem with how to avoid receiving a negative number for subtraction.

My objective is to randomly generate a mathematical equation and save the answer to ,then check if the user is entering the correct answer.

My attempts:
------------

1) I tried to have two temp variables to store two random numbers ,then allocate the larger number to 'x' and smaller on to 'y'.

2) I also tried to have one temp variable to hold the value of 'x' (if larger than 'y') then switch the x and y variables, with temp holding the 'x' variable.

*Error encountered (in both attempts) *
---------------------------------------

7208908 (black square) 1961740832 = -2

2] Code :
==========

 ``12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667`` `````` struct MathEq{ public: int x; int y; char symb = {'+','-','/','\*'}; char s; MathEq(); int answer(int x,int y,int s); int getX(){ return x; } int getY(){ return y; } char getSymbol(){ return s; } }; MathEq::MathEq(){ srand(time(NULL)); int temp=0; int index = (rand() % 4) +1; s = symb[index]; if(s == '/' || s == '*'){ x = (rand() % 12) +1; y = (rand() % 12) +1; } if(s == '+' || s == '-'){ x = (rand() % 100) +1; y = (rand() % 100) +1; } } int answer(int x,int y,char s){ int a =0; switch(s){ case '+': a = x + y; break; case '-': a = x - y; break; case '/': a = x / y; break; case '*': a = x * y; break; return a; } } ``````

 ``12345678`` ``````int main(){ MathEq m; int answerM = answer(m.getX(),m.getY(),m.getSymbol()); cout<< "Result is: "<
Last edited on int index = (rand() % 4) +1;
s = symb[index];

this says take an number from 0-3 and add 1, its now 1-4.
symb is .
arrays are zero indexed. so symb supports , , , and . 4 is out of bounds and zero is unreachable, the +1 is not correct.

Registered users can post here. Sign in or register to post.