shoham
shoham

Reputation: 812

C - random number generation

newbie in C here. I'm trying to have a different value for a variable everytime I run a program. I have this code:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ADD 1
#define SUB 2
#define MUL 3
#define DIV 4

int main(void)
{
    double out;
    int choice;
    float x, y;
    printf("Welcome to our first calculator program!\n");
    printf("===========================\n");
    printf("Please insert 2 numbers:\n");
    scanf("%f%f", &x, &y);
    choice = 1 + srand(time(NULL)) % 4;
    if(choice == ADD)
            out = x + y;
    else if(choice == SUB)
            out = x - y;
    else if(choice == MUL)
            out = x * y;
    else
    {
            if(y != 0)
                    out = x / y;
            else
            {
                    out = 0;
                    fprintf(stderr, "error");
                    return 1;
            }
    }
    printf("The outcome is: %0.2lf\n", out);
    return 0;
}

but it always gives me 4 in choice. I don't get why...

Can you help me? Thanks.

Upvotes: 1

Views: 208

Answers (2)

Morten Jensen
Morten Jensen

Reputation: 5946

Right now you are calling srand and expecting a random number. You should seed the entropy pool by calling srand and THEN calling rand to get the random number :)

An example of usage taken from: http://www.cplusplus.com/reference/cstdlib/srand/

int main ()
{
  printf ("First number: %d\n", rand()%100);
  srand (time(NULL));
  printf ("Random number: %d\n", rand()%100);
  srand (1);
  printf ("Again the first number: %d\n", rand()%100);

  return 0;
}

See how you seed by calling srand and then retrieve the random integer from rand

You need to do this:

srand(time(NULL));
choice = 1 + rand() % 4;

instead of this:

choice = 1 + srand(time(NULL)) % 4;

Upvotes: 3

Ed Heal
Ed Heal

Reputation: 60027

You need to seed the random number generator - see srand - http://linux.die.net/man/3/srand.

Use something like the current time.

Then use rand to get a random number

Upvotes: 1

Related Questions