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?

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.

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

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

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!

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/

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

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 developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.