[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 :
==========

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
  struct MathEq{
    public:
    int x;
    int y;
    char symb[4] = {'+','-','/','\*'};
    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;
    }
}


1
2
3
4
5
6
7
8
int main(){
    MathEq  m;

    int answerM = answer(m.getX(),m.getY(),m.getSymbol());

    cout<< "Result is: "<<m.getX()<<" "<< m.getSymbol()<<" "<< m.getY() << " = "<< answerM<<endl;

}
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 [4].
arrays are zero indexed. so symb supports [0], [1], [2], and [3]. 4 is out of bounds and zero is unreachable, the +1 is not correct.

Topic archived. No new replies allowed.