Click here to Skip to main content
15,891,184 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi,

I have made this random program but I am keep getting the same answer as 41. Any help to get a random number between 1 to 100 each time I run the program rather then 41 only.
C++
void main()
{
	int userData;
	int random;

	printf("\t\t\t Lotto Game \n");
	printf("\t\t\t ---------- \n\n");
	printf("Enter a number to see if you have win a price : ");
	scanf("%d%*c",&userData);
	random = rand() ;
	
	if (userData > random)
	{
		printf("Your entry is higher\n");

	}

	else if (userData < random)
	{
		printf("Your entry is lower\n");
	}

	else 
	{
		printf("Corrent answer, you are a winner :-)\n");
	}

	printf("Correct answer is %d \n",random);


	system("pause\n");

}
Posted
Updated 7-Jul-12 5:45am
v2
Comments
Sergey Alexandrovich Kryukov 7-Jul-12 11:52am    
Are you writing a computer game for mentally retarded children? :-)
--SA
Salman Ali Hero 12-Jul-12 1:15am    
ha ha ha, I am thinking to upload this app on Itunes and make $$lol

Since you are only doing this once in your program it will generally return the same number. You need to seed the randomiser via the srand()[^] function, using a seed value that is unique, something like the current time would be a reasonable choice.
 
Share this answer
 
Comments
Salman Ali Hero 7-Jul-12 12:05pm    
Thanks, solved my problem
As you can read from this[^] you need to initialize the random number generator (using the srand function[^]) before calling the rand function it.

Example from the reference link:
C++
/* rand example: guess the number */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main ()
{
  int iSecret, iGuess;

  /* initialize random seed: */
  srand ( time(NULL) );

  /* generate secret number: */
  iSecret = rand() % 10 + 1;

  do {
    printf ("Guess the number (1 to 10): ");
    scanf ("%d",&iGuess);
    if (iSecret<iGuess) puts ("The secret number is lower");
    else if (iSecret>iGuess) puts ("The secret number is higher");
  } while (iSecret!=iGuess);

  puts ("Congratulations!");
  return 0;
}
 
Share this answer
 
Comments
Salman Ali Hero 7-Jul-12 12:05pm    
Thanks, solved my problem
André Kraak 7-Jul-12 12:06pm    
Your welcome.
Sergey Alexandrovich Kryukov 7-Jul-12 13:08pm    
Right, a 5. We answered at the same time.
--SA
Randomize (seed) the pseudo-random number generator using srand, as shown in the code sample below:
http://www.cplusplus.com/reference/clibrary/cstdlib/rand/[^].

Do it only once per run time!

—SA
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900