Thread: random function problem

  1. #1
    Registered User
    Join Date
    Feb 2008
    Posts
    28

    random function problem

    PHP Code:
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    #include <time.h>

    int random(int num);

    main()
    {
         while(
    1)
         {
                 
         
    int timer time(NULL);
         
    int variable[100];
         
    int i=0j=0;
         
         
         
    sleep(1);
         
    srand(timer);
         
         
         
    variable[i] = random(23);
         
    printf("Random #: %d\t"variable[i]);     
         
    scanf("%f", &variable);
         }
         return;
    }

    int random(int num)
    {
        return((
    rand()/(RAND_MAX+1.0))*num);

    when this exicutes i just keep getting 22 as number instead of another number. can some one help me

  2. #2
    Chinese pâté foxman's Avatar
    Join Date
    Jul 2007
    Location
    Canada
    Posts
    404
    You should call srand only once, not on every loop iteration.
    I hate real numbers.

  3. #3
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    Quote Originally Posted by foxman View Post
    You should call srand only once, not on every loop iteration.
    And this is explained in the FAQ - check it out!
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  4. #4
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    main() - read FAQ: main() / void main() / int main() / int main(void) / int main(int argc, char *argv[])

    int i=0, - do you realize that having this inside the loop you are acessing the same variable[0] member on every iteration of the loop?

    Code:
    scanf("&#37;f", &variable);
    variable is integer array - what is this code should do? check the crash resistence of your system?

    return; - main returns int
    use
    Code:
    return 0;
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 8
    Last Post: 10-29-2008, 06:33 AM
  2. doubt in c parser coding
    By akshara.sinha in forum C Programming
    Replies: 4
    Last Post: 12-23-2007, 01:49 PM
  3. We Got _DEBUG Errors
    By Tonto in forum Windows Programming
    Replies: 5
    Last Post: 12-22-2006, 05:45 PM
  4. Replies: 3
    Last Post: 03-04-2005, 02:46 PM
  5. Replies: 6
    Last Post: 03-02-2005, 02:45 AM