I have a simple function that is giving me this error:
error: expected delcaration specifiers or '...' before 'time'
here is the code in the file:
#include <stdlib.h>
#include <time.h>
srand(time(NULL));
float random_number(float min, float max) {
float difference = (max - min);
return (((float)(difference + 1)/RAND_MAX) * rand() + min);
}
i dont get why im getting this error. I'm compiling with gcc in Ubuntu 12.04.
In the C language, all code that is executed at runtime must be inside a function. Put the call to srand()
inside an init function.
You cannot have call to functions outside the main function scope, also, there is no sense in seeding random just before you use it in function random_number
you need to move srand(time(NULL));
to main function, like:
float random_number(float min, float max) {
float difference = (max - min);
return (((float)(difference + 1)/RAND_MAX) * rand() + min);
}
int main()
{
srand(time(NULL));
// your code which calls random_number here
}
another approach, do not change main, but:
static int isRandomInited = 0;
float random_number(float min, float max) {
if (!isRandomInited) { // init random only 1 time
srand(time(NULL));
isRandomInited = 1;
}
float difference = (max - min);
return (((float)(difference + 1)/RAND_MAX) * rand() + min);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With