Thread: Rand function

  1. #1
    Registered User
    Join Date
    Dec 2017
    Posts
    7

    Rand function

    I'm trying to generate numbers between -1 and 1 using the rand() function so i can pass random values to the two members of N structs but the program prints the same values N times. Any advice?
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    struct Complex
    {
        double x;
        double y;
    };
    int main ()
    {
        int N,i,j,k;
        struct Complex *comp;
        printf("Enter N:\n");
        scanf("%d",&N);
           comp = malloc(N*sizeof(struct Complex));
        if (comp == NULL)
        {
            printf("Error! Out of memory");
            return 1;
        }
    
    
        for (j=0;j<N;j++){            
    srand ( time ( NULL));
    
    
           (comp + j)->x = (double)rand()/RAND_MAX*2.0-1.0;  
    
    
           (comp + j)->y = (double)rand()/RAND_MAX*2.0-1.0;   
        }
        for (i=0; i<N; i++)
        {
            printf("\n%f\t%f",(comp + i)->x,(comp + i)->y);
        }
    return 0;

  2. #2
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    2,738
    Use srand() only once, preferably at the beginning of your program. Don't call it repeatedly.
    Devoted my life to programming...

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. about rand() function.
    By IS La M in forum C Programming
    Replies: 7
    Last Post: 01-17-2016, 06:44 AM
  2. Replies: 2
    Last Post: 11-14-2011, 08:08 AM
  3. rand() function
    By thunderzone in forum C Programming
    Replies: 10
    Last Post: 05-02-2010, 07:09 AM
  4. rand() function
    By jduke44 in forum C Programming
    Replies: 9
    Last Post: 10-07-2005, 05:33 PM
  5. I need help using the rand() function
    By incognito in forum C++ Programming
    Replies: 14
    Last Post: 06-02-2002, 02:48 PM

Tags for this Thread