Thread: Help Please

  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
    4,632
    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 int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    > #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.

Popular pages Recent additions subscribe to a feed

Tags for this Thread