I am having a problem displaying random numbers, I'm trying to make a dice game where you play against the computer and the first one to 100 wins. However, my random number is never random, it always comes out as the same number.

From what I understand to simply display a random number in the console is,

#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
  int i;

  i = rand();
  cout << i;

  return 0;
}

The problem is that I ALWAYS get the number 41 from this program, no matter how many times i run it.

I've changed it to work like a die;

#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
  int i;

  i = (rand()%6)+1;
  cout << i;

  return 0;
}

And from that, I always get the number 6. Basically its not coming out as a random number and I can't figure out why. Can anyone tell me what I'm doing wrong?

Re: C++ Random number generator 80 80

You need to use srand() to seed rand before you use it. For a game like yours i would use srand((unsigned)time(0)); . You will need to use #include <ctime> in your code to do this.

Re: C++ Random number generator 80 80

Thanks for the reply Nathan, but could you perhaps give me a simple example of that? I've never used that command and it would really help if I could see it in use

Re: C++ Random number generator 80 80

Doen't your book explain it? Or your tutorial site? What about Google?

Re: C++ Random number generator 80 80

Alright, I think I got it,

#include <cstdlib> 
#include <ctime> 
#include <iostream>
 
using namespace std;
 
int main() 
{ 
    srand((unsigned)time(0)); 

    int i;
	i = (rand()%6)+1; 

	cout << i << "\n"; 

}

Thanks for the help!

Re: C++ Random number generator 80 80

To solve the problem you can use "ctime" library and the function srand().

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{
int i, r;

srand(time(0));

for(i = 0; r <= 20000; i++)
r = rand();

cout << "Number is " << r << ". It was generated on try number " << i << ".\n";

return 0;
}

just look here:

http://www.cplusplus.com/forum/beginner/5131/

Re: C++ Random number generator 80 80

i am making hangman game and i want the program to pick up random wrds... how can i do it???

Re: C++ Random number generator 80 80

i am making hangman game and i want the program to pick up random wrds... how can i do it???

I haven't done anything similar to it, but you'd need database which contains words.
And you'll need some "Input/Output with files" skills to get words from database ( for example some *.txt file which contains words, unless you are going to make a huge code by writing all words in a code...within some struct... sounds bad idea ).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.19 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.