I wrote a code with a float array like this:
float array[3] = {rand(), rand(), rand(), rand()};
But every time i run the code, I get {42, 3745, 183, 925}. How can I get new values for array on every new run?
I wrote a code with a float array like this:
float array[3] = {rand(), rand(), rand(), rand()};
But every time i run the code, I get {42, 3745, 183, 925}. How can I get new values for array on every new run?
You should be using the srand
function prior to your calls to rand
. From the C99 Standard,
The srand function uses the argument as a seed for a new sequence of pseudo-random numbers to be returned by subsequent calls to rand. If srand is then called with the same seed value, the sequence of pseudo-number numbers shall be repeated. If rand is called before any calls to srand have been made, the same sequence shall be generated as when srand is first called with a seed value of 1.
So the seed has been set automatically for you and the same seed is being set every time you run the program.
A common practice is to set the seed to the current time.
For example, if you run the below program multiple times, you should not be getting the same numbers each time unless you run the program in rapid succession such that (unsigned) time(NULL)
evaluates to the same value.
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main(void) {
/* initializes random number generator. time returns current time.
Passing it's return value prevents the same numbers from being
generated each time we run the program */
srand((unsigned) time(NULL));
/* generate three pseudo-random integers in [0, RAND_MAX] */
printf("(%d, %d, %d)\n", rand(), rand(), rand());
return 0;
}
I think this would solve your problem
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(){
srand(time(0));
float array[4] = {rand(), rand(), rand(), rand()};
printf("%.2f %.2f %.2f %.2f\n",array[0], array[1], array[2], array[3]);
return 0;
}