Can you tell me the code how to generate random numbers from 5-10 or tell me any links thanks.
This is a discussion on Generating Random Numbers within the C++ Programming forums, part of the General Programming Boards category; Can you tell me the code how to generate random numbers from 5-10 or tell me any links thanks....
Can you tell me the code how to generate random numbers from 5-10 or tell me any links thanks.
Code:#include <stdlib.h> #include <stdio.h> #include <time.h> inline int rand_mid(int low, int high) { return (rand() * (high - low)) / RAND_MAX + low; } int main(void) { int x; srand(time(NULL)); x = rand_mid(5, 10); printf("A random number from 5 to 10: %d\n", x); return 0; }
Thanks just wondering can u redo it so it has comments just so i'm not mis-interpreting some parts of it.
Code:#include <stdlib.h> //for rand, srand, and RAND_MAX #include <stdio.h> //for printf and you already know this ;p #include <time.h> //for time to seed rand /*This function is declared as inline, meaning it is treated as a **macro instead of a function...this causes less overhead */ inline int rand_mid(int low, int high) { /*take low out of high (subtract), then multiply the result **by a random number. Divide that result by the constant **RAND_MAX from stdlib and add low to that. The result is **a pseudo-random number within the bounds of low and high */ return (rand() * (high - low)) / RAND_MAX + low; } int main(void) { int x; /*seed rand, this is done so that you don't get the same **set of random numbers every time you run the program **so you set the seed to the current time, which creates **pretty good random numbers. */ srand(time(NULL)); /*pass 5 and 10 as low and high to rand_mid, then **assign the value returned to x and print it out */ x = rand_mid(5, 10); printf("A random number from 5 to 10: %d\n", x); return 0; }