1

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.

3
  • 1
    Are you sure that code compiles? srand (or "seed random") should have a void return type, and rand should be used to get the actual random number. Commented Feb 26, 2014 at 22:19
  • 1
    @user2864740 gcc version 4.7.2 (Debian 4.7.2-5) complains error: void value not ignored as it ought to be. Commented Feb 26, 2014 at 22:35
  • 1
    @user2864740 Visual Studio 2010 complains also: error C2296: '%' : illegal, left operand has type 'void' .. Wonder which compiler allows this :) ? Commented Feb 27, 2014 at 9:21

2 Answers 2

3

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;
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.