srand rand. return always the same value

This is a discussion on srand rand. return always the same value within the C Programming forums, part of the General Programming Boards category; Hi I wrote a funct my_random(limit) that 'should' return a pseudor-random value between 0 and limit-1, then I have a ...

  1. #1
    Registered User
    Join Date
    Jun 2009
    Posts
    56

    srand rand. return always the same value

    Hi

    I wrote a funct my_random(limit) that 'should' return a pseudor-random value between 0 and limit-1, then I have a small prog like:

    Code:
    main_prog.c
    ..............
    int random_value;
    ............. 
    srand(time(NULL)); // 
              random_value= my_random(limit); // here I call my funct
    ....
    where my_random looks like

    Code:
    int my_random(int val){
    
    int rand_choice=0;
    	rand_choice=rand()%(val);
            printf("%d\n",rand_choice);
    
    return rand_choice;
    }
    the problem in that i get always the same value. I'm reading some tutorials and I know that is important to choice the right place where put the srand(seed).
    But I belived that outside the function should be enough, otherwise where should be the right position?

    Thanks
    D

  2. #2
    gcc -Wall -pedantic *.c
    Join Date
    Jan 2009
    Location
    London
    Posts
    60
    Code:
    main_prog.c
    ..............
    int random_value;
    ............. 
    srand(time(NULL)); // 
              random_value= my_random(limit); // here I call my funct
    ....
    Where did you declare ant initialize the variable limit?

  3. #3
    Registered User
    Join Date
    Jun 2009
    Posts
    56
    In main_prog.c.

    Limit is an input value.

  4. #4
    gcc -Wall -pedantic *.c
    Join Date
    Jan 2009
    Location
    London
    Posts
    60
    ..Try to put the srand() call as you wrote it, in the function as you don't use rand().

  5. #5
    Registered User
    Join Date
    Jun 2009
    Posts
    56
    already done.
    I've tried to put srand in:

    -the function my_rand()----->but i still get the same values
    -in the top of main but i get an error like:

    Code:
    main.c:52: error: expected ‘)’ before ‘(’ token
    main.c: In function ‘create_new_outfiles’:
    main.c:705: warning: ignoring return value of ‘system’, declared with attribute warn_unused_result
    make[2]: *** [main.o] Error 1

  6. #6
    Registered User
    Join Date
    Jun 2009
    Posts
    56
    Hi

    I solved the error in the main and i wrote srand after the main, now it works

    Thanks

    D

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