Aug 30, 2009 at 7:57pm UTC
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;
}
Aug 30, 2009 at 7:59pm UTC
Just a quick glance at your code, = is assignment operator. Comparison operator is ==
Last edited on Aug 30, 2009 at 8:00pm UTC
Aug 30, 2009 at 8:10pm UTC
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 Aug 30, 2009 at 8:12pm UTC
Aug 30, 2009 at 8:22pm UTC
ok cool thanks for the repsonse.
Aug 30, 2009 at 10:21pm UTC
Also how do I make it repeat until I guess the right number?
Aug 30, 2009 at 11:13pm UTC
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 Aug 30, 2009 at 11:14pm UTC