Help Please

This is a discussion on Help Please within the C Programming forums, part of the General Programming Boards category; The program is supposed to be printing 21 different numbers that are randomly generated. Why am I getting the same ...

  1. #1
    Registered User
    Join Date
    Mar 2014
    Posts
    8

    Help Please

    The program is supposed to be printing 21 different numbers that are randomly generated. Why am I getting the same number 21 times?
    Using dev C++ compiler.



    Code:
    /*prints random numbers between 1 - 99*/
    
    
    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    
    
    #define MAXR 99;
    #define MINR 2;
    
    
    
    
    double random(void);
    
    
    int main(void)
    {
      
      double sides[7][3];
      double ran_num;
      int i, n;
      
      for(n=0;n<3;n++)
      {        
      for(i=0;i<7;i++)
         {            
         ran_num = random();
         sides[i][n] = ran_num++;
         }
      }
      
      for(n=0;n<3;n++)
      { 
         printf("\n\n") ;  
         for(i=0;i<7;i++)
         {
            printf("%.2f      ", sides[i][n]);
         }
      }
      
      system("PAUSE");    
      return 0;
    }
    
    
    double
    random(void)
    {
       srand(time(NULL));
       int r;
       r = rand()%MAXR + MINR;
       return(r);
    }

  2. #2
    Registered User
    Join Date
    May 2010
    Posts
    2,805
    Probably because you have srand() in your function. This function should be called once and only once, usually early in main().

    Jim

  3. #3
    Registered User
    Join Date
    Mar 2014
    Posts
    8
    That fixed it, thanks!

  4. #4
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,673
    > #define MAXR 99;
    > #define MINR 2;
    Also, remove the ; from the ends of #defines, unless you really mean to have a ; there.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

Popular pages Recent additions subscribe to a feed

Tags for this Thread


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