I am new in programming. I need something which can generate random number with C. I found "rand()". But it is not generating random values. Please check the following simple code.
The following code gives
roll the first dice : 6
roll the second dice : 6
roll the third dice : 5
Here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
int main()
{
int dice1,dice2,dice3,total1,total2;
char prediction[10];
int dice_generator()
{
dice1= (rand()%6)+1;
printf("roll the first dice: %d \n", dice1);
dice2= (rand()%6)+1;
printf("roll the second dice: %d \n", dice2);
dice3= (rand()%6)+1;
printf("roll the third dice: %d \n", dice3);
return 0;
}
dice_generator();
total1 = dice1+dice2+dice3;
printf("final value is = %d\n",total1);
return 0;
}
You need to "seed" the random number generator. Try calling
srand(time(NULL));
once at the top of your program.
(There are better ways, but this should get you started.)
Firstly, C language does not support nested functions. It is illegal to define dice_generator() inside the definition of main() as in your code. Your compiler might support this, but in any case this is not C.
Secondly, rand() does not generate random numbers. rand() produces a seemingly "erratic" but perfectly deterministic sequence of integers, which begins at some initial number and always follows the same path. All you can do is make rand() start its sequence from a different "seed" number by calling srand with a new seed as an argument.
By default rand() is required to work as if you called srand(1) in order to seed the sequence.
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