Bracketing Search

Hey guys so this is my first post!

When I was doing the bracketing search problem from this page: http://cplusplus.com/forum/articles/12974/, I ran into trouble with the random number generation. When I call the random number function through the while loop, the program gives me a random answer (i.e it tells me 5 is correct when I put in 3).

Here's the source so hopefully this helps.

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
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <ctime>
using namespace std;

int rand1to10();

int main() {
	srand(time(NULL));
	int answer;

	cout << "Enter a number between 1 and 10." << endl;
	cin >> answer;
	if (answer < 1 || answer > 10) {
		cout << "You must enter a valid number." << endl;
		cin >> answer;
	}
	
	while(true){
		rand1to10();
		
		if (answer == rand1to10()){
			cout << rand1to10() << " is the right answer."; 
			break;
		}
		else {
			cout << rand1to10() << endl;
		}
	}
	return 0;
}

int rand1to10() {
	return rand() % 10 + 1; 
}
Every call to rand1to10 returns a random number. The number you generate and compare to answer is probably not the same value you get when you feed it to cout.

1
2
3
4
5
6
7
8
9
10
11
	while(true){
		int guess = rand1to10();
		
		if (answer == guess){
			cout << guess << " is the right answer."; 
			break;
		}
		else {
			cout << guess << endl;
		}
	}
Cool that worked!
Topic archived. No new replies allowed.