RAND

I'm trying to do the bracketing search exercise from http://www.cplusplus.com/forum/articles/12974/ but am having trouble with the second to last part. Specifically, I can't manage telling the computer that the number it guessed is too low.

(In the following code, z is a number between 0 and 99)
1
2
3
4
5
6
7
8
9
10
11
  else if(x=3)
       {
        int x=100-z;
        z=rand() % x + z;
        cout<<z<<"\n";
        cout<<"Is this the correct number?\n";
        cout<<"1. Yes\n";
        cout<<"2. Too high\n";
        cout<<"3. Too low\n";
        cin>>x;
       }


And here's the full code if you want it (feel free to point out any other mistakes I may have made)
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
#include <iostream>
#include <stdlib.h>;

using namespace std;

int main()
{
   cout<<"Enter a number for the computer to guess.";
   int y;
   int z;
   cin>>y;
   int x=0;
   while(x!=1)
   {
       if(x=0)
       {
        z=rand() % 100+1;
        cout<<z<<"\n";
        cout<<"Is this the correct number?\n";
        cout<<"1. Yes\n";
        cout<<"2. Too high\n";
        cout<<"3. Too low\n";
        cin>>x;
       }
      else if(x=2)
       {
        z=rand() % z;
        cout<<z<<"\n";
        cout<<"Is this the correct number?\n";
        cout<<"1. Yes\n";
        cout<<"2. Too high\n";
        cout<<"3. Too low\n";
        cin>>x;
       }
       else if(x=3)
       {
        int x=100-z;
        z=rand() % x + z;
        cout<<z<<"\n";
        cout<<"Is this the correct number?\n";
        cout<<"1. Yes\n";
        cout<<"2. Too high\n";
        cout<<"3. Too low\n";
        cin>>x;
       }
       else
       {
           x=1;
       }

   }

cout<<"Your number is"<<y;
}
At lines 15, 25 and 35, you seem to be confusing the assignment operator = with the equality comparison operator ==.

(x=0) will always evaluate to 0, which is equivalent to false. So that block will never execute.

(x=2) will always evaluate to 2, which is equivalent to true. So that block will always execute.

The else if(x=3) block will never execute, because the else if(x=2) block will always execute.
Last edited on
Topic archived. No new replies allowed.