0

So I am currently learning C, and I have some confusion about how the random() function works. I know I have to provide a seed, but I don't know how to actually generate the random number.

srandom(seed);
long int value= random(40);

When I try this it gives me a compiler error:

too many arguments to function ‘long int random()

The end goal is to get a random number between 1 and 40. I should add that the goal is to not use the rand() function.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Jim Gaf.
  • 31
  • 1
  • 1
  • 3
  • 3
    random doesn't take arguments; you passed the value 40. – duffymo Feb 25 '17 at 18:17
  • Please do not place `srand()` before each call to `rand()`. Call it once at the start of the program. I do not know why you renamed those library functions. What are they? How can we know what they do? Are they non-standard functions or your own? – Weather Vane Feb 25 '17 at 18:22
  • Read the POSIX specification for [`random()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/random.html) — it tells you a lot of what to do. For the rest, read [Is this C implementation of Fisher-Yates shuffle correct?](http://stackoverflow.com/a/3348142) to see how to generate an unbiassed random number in the range 0..N (for 1..40, you'll use a random number in the range 0..39 and add 1). – Jonathan Leffler Feb 25 '17 at 21:34

3 Answers3

6

The answer to your question is precisely answered by the compiler. You are passing '40' to the function random() which it is not supposed to receive.

The signature for random() is:

long int random (void) 

void keyword here is indicator that the function in hand is not supposed to receive anything.

Here's an example program to generate 6 random numbers.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int num;
    int max = 5; 
    for (int c = 0; c <= max; c++){
      num = random();
      printf("%d\n",num);         
   }
   return 0;
}

Output:

fire-trail@Sahai-Yantra:~$ gcc try.c 
fire-trail@Sahai-Yantra:~$ ./a.out
1804289383
846930886
1681692777
1714636915
1957747793
424238335

To reach your end goal of generating random numbers within a given range using random(), see How to generate a random number from within a range.

Community
  • 1
  • 1
3

The answer is right there in the error thrown by the compiler

too many arguments to function ‘long int random()

Change random(40) to random()

Aniruddh Dikhit
  • 662
  • 4
  • 10
2

There is no argument in random() function.

See man page of random(). Prototype of random()

long int random(void);
msc
  • 33,420
  • 29
  • 119
  • 214