hi,
i want to create a program that will randomly give me a number between 0 and 11 everytime i call the function.
is there a math function that will automatically do this for me?
barneygumble742
hi,
i want to create a program that will randomly give me a number between 0 and 11 everytime i call the function.
is there a math function that will automatically do this for me?
barneygumble742
The function you're looking for is rand, from cstdlib:
rand returns a value in the range [0,RAND_MAX), so you'll need to force the range down into what you want. When you say between 0 and 11, I'm assuming that the valid numbers are 1,2,3,4,5,6,7,8,9, and 10, which is why I force the range into [0,10) with the remainder operator and then add 1.Code:#include <cstdlib> #include <iostream> using namespace std; int main() { for ( int i = 0; i < 10; i++ ) { int r = 1 + rand() % 10; cout<< r <<'\n'; } }
You probably also want to look up the srand function if you find that you need a different sequence with every run of the program.
My best code is written with the delete key.