problem with random numbers

This is a discussion on problem with random numbers within the C Programming forums, part of the General Programming Boards category; hi i just made a program to practice random numbers because im new . i get different numbers each time, ...

  1. #1
    Registered User
    Join Date
    Sep 2005

    problem with random numbers

    hi i just made a program to practice random numbers because im new . i get different numbers each time, but every time i run the program they are the same numbers each time. anyone know the problem? thanks in advance.

    int number(void);
    main() { 
           printf("hit a key to quit");
           return 0;
    int  number(){
         int fy=1,fz=100,fx;
         fx=rand() % (fz-fy+1);
         printf("Your number is %d\n",fx);
         return fx;

  2. #2
    Registered User fischerandom's Avatar
    Join Date
    Aug 2005
    What you are talking about is not random numbers, they are pseudo-random numbers. A pseudo-random generator such as the standard C library function rand( ) uses a start seed and from that start seed there will be a mathematically defined sequence of pseudo-random numbers returned each time it is called. To get a new sequence each time you run your program you need to set a different seed with srand( ). This can be accomplished by using the current time like this:
    #include <stdlib.h>
    #include <stdio.h>
    #include <time.h>
    int  main( ) {
     int  n;
     srand( time( 0 ) );  /* Generate a new seed */
     for ( n = 0; n < 100; ++n )
      printf( "%i, ", rand( ) );
     return 0;
    Bobby Fischer Live Radio Interviews

  3. #3
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    See Prelude's site.

    Last edited by dwks; 11-24-2005 at 09:00 AM.

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell

    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ:

    My website:
    Projects: codeform, xuni, atlantis, nort, etc.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem with random numbers
    By yaya in forum C++ Programming
    Replies: 6
    Last Post: 05-30-2007, 11:30 AM
  2. Problem with random number generation
    By HAssan in forum C Programming
    Replies: 1
    Last Post: 03-27-2007, 06:49 PM
  3. Random Problem?
    By dizz in forum C++ Programming
    Replies: 4
    Last Post: 11-20-2002, 05:00 PM
  4. random double numbers
    By Gugge in forum C Programming
    Replies: 7
    Last Post: 05-18-2002, 12:26 AM
  5. Promlems with Random Numbers
    By Unregistered in forum C++ Programming
    Replies: 13
    Last Post: 03-20-2002, 08:46 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21