number guessing game problem

I’ve been trying to make a game that makes a random number and you have to guess it. But when I put in a number it gives me all 3 of the possible answers. I’m sure its a simple fix but I cant figure it out :D


#include <cstdlib>
#include <iostream>

using namespace std;

int main()

{

int a = rand();
int b;

cout << "enter random number " << endl;
cin >> b;

if (b = a);
cout << "you win" << endl;

if (b < a);
cout << "too low" << endl;

if (b > a);
cout << "too high" << endl;


system("PAUSE");

return 0;

}
Just a quick glance at your code, = is assignment operator. Comparison operator is ==
Last edited on
except that '=' operator you need to change several other things:

1.

if (b < a);
What you have done here is empty controlled statement, so delete that semicolon if you want your code below to be executed properly (otherwise it will be like you mentioned in your post)

2.

int a = rand();

This is not enough - you will always get the same number, because you forgot to initialize the random number generator.
For more info check here:
http://www.cplusplus.com/reference/clibrary/cstdlib/srand/
and here's a sample:
1
2
3
#include <ctime>
//..
srand((unsigned) time(NULL));


3.

Avoid using system(). For more info read this:
http://www.cplusplus.com/forum/articles/11153/
and this: http://www.cplusplus.com/forum/beginner/1988/
(to learn how to keep your console opened)
Last edited on
ok cool thanks for the repsonse.
Also how do I make it repeat until I guess the right number?
Why use NULL?
Why not put 0?

Hint: C pre-processor.



And using rand like that isn't very 'robust'.

Try this:
1
2
3
srand((unsigned)time(0));
int floor = 0, ceil = 10, range = (ceil - floor);
int rnd = floor + int(range * rand() / (RAND_MAX + 1.0);


Add 1 to range if you want it to be inclusive, i.e. from 0-10 not 0-9.

To make it repeat:
Try a loop.
ok i see now cool.
Yup, sorry, don't use NULL (deprecated) in C++ - my bad (habit)

and Yes, rand() isn't that good for long spans, however for short ones it's not that bad to use it i.e.
int number = rand() % 6 + 1; //1-6
Last edited on
Topic archived. No new replies allowed.