C random number, random number
1
Before talking about this question, let's talk about the role and usage of srand.
Srand () function:
Prototype: void srand (unsigned seed)
Function: starts when a random number is generated. This function is used with the rand function.
Header file: stdlib. h time. h
Example:
#include <stdio.h>#include <stdlib.h>#include <time.h>int main(void) { int i; time_t t; srand((unsigned) time(&t)); printf("Ten random numbers from 0 to 99\n\n"); for (i=0; i<10; i++) printf("%d\n", rand()%100); return 0;}
When you run the program, you will find that the random numbers generated each time are different. This is because time is used as the seed, and time is different all the time, so a random number is generated. Therefore, to generate different random numbers, you must call srand before using rand.
2
If the code is changed
#include <stdio.h>#include <stdlib.h>#include <time.h>int main(void) { int i; //time_t t; printf("Ten random numbers from 0 to 99\n\n"); for (i=0; i<10; i++) { srand((unsigned) time(NULL)); printf("%d\n", rand()%100); } return 0; }
The numbers output are the same, indicating that rand should be placed inside the loop, and srand should be placed outside the loop.
#include <stdio.h>#include <stdlib.h>#include <time.h>int main(void){ int i; srand((unsigned) time(NULL)); printf("Ten random numbers from 0 to 99\n\n"); for (i=0; i<10; i++) printf("%d\n", rand()%100); return 0;}
In this way, 10 random numbers are output.
#include <stdio.h>#include <stdlib.h>#include <time.h> int main(void) { int i; srand((unsigned) time(NULL)); printf("3 random numbers from 0 to 99\n\n"); printf("%d\n", rand()%100); printf("%d\n", rand()%100); printf("%d\n", rand()%100); return 0;}
This also outputs three random numbers. Do not use srand (unsigned) time (NULL) again before rand.
3. Random Number and absolute processing with decimal point
The Return Value of the rand () function is the number between-90 and 32767...
Pseudocode:
If one decimal (float) (rand () % 10 + 10)/10.0f;
If two decimal places (float) (rand () % 100 + 100)/100366f;
#include <stdio.h>#include <stdlib.h>#include <time.h>int main(void) { int i; srand(time(NULL)); for (i=0; i<10; i++) { printf("%f\n", (abs(rand())%10000+10000)/10000.0-1.00); } return 0;}