Stupid question about rand() and srand()

This is a discussion on Stupid question about rand() and srand() within the C Programming forums, part of the General Programming Boards category; I looked up the syntax of rand() and srand() and I was wondering if anyone can give me a better ...

  1. #1
    Unregistered
    Guest

    Stupid question about rand() and srand()

    I looked up the syntax of rand() and srand() and I was wondering if anyone can give me a better understanding of the way they work and how to use them.

  2. #2
    Unregistered
    Guest
    #include <stdio.h>
    #include <time.h>
    #include <stdlib.h>
    #include <conio.h>

    int main (void)
    {
    int userInput = 0;
    int NumberOfGoes = 0;
    int x;

    srand( (unsigned)time( NULL ) ); /*rand seeded with time*/
    x=(rand() %(5+1)); /* x takes value of rand */
    /*rand limited to five*/
    /*change to make it harder, i.e 30+1 */
    printf ("\n Please enter a number between 1 and 5");
    printf ("\n to try and pick the same number as the computer!: ");

    while (NumberOfGoes < 5)
    {


    scanf ("%i", &userInput);
    if (userInput >5 )
    {
    printf ("\n Choice is out of range, try again!!!\n\n");
    }
    else if (x !=userInput && x<userInput )
    {
    printf ("\nThe number does not match\n" );
    printf("\n\"Too High\" ");
    printf ("\n Choose a lower number: ");
    }
    else if (x !=userInput && x>userInput )
    {
    printf ("\nThe number does not match\n");
    printf ("\n\"Too Low\" ");
    printf ("\n Choose a Higher number: ");
    }
    else if (x == userInput)
    {
    printf ("\n That is correct\n");
    system("PAUSE");
    return(0);
    }
    NumberOfGoes++;
    }
    printf ("\n\n\nThe number of inputs has reached five ");
    printf ("\nThe number was\n **%d** \n",x);

    system("PAUSE");
    return(0);
    }

  3. #3
    Registered User
    Join Date
    Dec 2001
    Posts
    88
    > x=(rand() %(5+1)) <

    mhm, what?

    do you mean
    x=rand()%5+1

    this generates a number form 1 to 5
    your code generates one from 0 to 5
    Hope you don't mind my bad english, I'm Austrian!

  4. #4
    Unregistered
    Guest
    Hi Shade
    Many thanks for pointing out my error, realised after posting.

Popular pages Recent additions subscribe to a feed

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