ECE 103 Engineering Programming Chapter 51 Random Numbers Herbert G. Mayer, PSU CS Status 6/4/2014 Initial content copied verbatim from ECE 103 material developed by Professor Phillip Wong @ PSU ECE
Syllabus srand() sand()
Random Number Generator C has library functions to input and output strings. Use #include <stdio.h> In the following table, char * is a pointer to a character array that contains a string. RNG Functions void srand (unsigned int seed) Initializes the RNG with a seed value int rand (void) Returns a pseudo-random integral number 2
String I/O Functions C has library functions to input and output strings. Use #include <stdio.h> In the following table, char * is a pointer to a character array that contains a string. int printf (const char * fmt, …) Prints formatted output to console int sprintf (char * s, const char * fmt, …) Prints formatted output to string int puts (const char * s) Prints string to console int scanf (const char * fmt, …) Reads formatted input from console int fgets (const char * s, FILE * stream) Reads string from input stream 3
srand int printf (const char * format, …) Writes formatted output to the console. Use the %s format specifier for strings. %s expects the address of a char array which contains a string. Example: char name[] = "Jane Doe"; printf("[%s]\n", name); → [Jane Doe] printf("[%s]\n", &name[0]); → [Jane Doe] printf("[%s]\n", &name[5]); → [Doe] 4
rand int sprintf (char * s, const char * format, …) Performs a formatted print and saves it to a string. Works like printf except the output is stored in string s. Nothing is printed to the console. Example: char str[50]; int x = 4; sprintf(str,"x=%d y=%f", x, 1.5f); printf("title = %s\n", str); 5