I am new to C language. When I try to generate a new number, I get the same random number every time. Also, I am trying to store the random number to a pre-declared array in the for loop, and retrieve it from another for loop, but the integer doesn't store in the array correctly.
How do I correctly generate a new random number every time, and how to store integer in the array?
Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
#include <time.h>
int main()
{
int randNum[4] = {0,0,0,0};
srand(time(NULL));
for(int i = 0; i < 4; i++)
{
if(fork() == 0)
{
randNum[i] = rand() % 100;
for(int j = 0; j < 4; j++)
{
printf("%d\t", randNum[j]);
}
exit(0);
}
wait(NULL);
}
}
printf prints the following each loop
84 0 0 0
0 84 0 0
0 0 84 0
0 0 84 0
Aucun commentaire:
Enregistrer un commentaire