I just learned how to make random numbers with the code below. I also just learned about functions. How would I use a function to return a random number between 11 and 23, inclusive. I have the random part down, I just am not sure how to return a function.
#include <iostream>
#include <time.h>
#include <stdlib.h>
usingnamespace std;
int randomNumber(int val1, int val2) // Function prototype
int main ()
{
int iseed = (int)time(NULL);
int randomNumber;
srand(iseed);
randomNumber = rand()%(23 - 11 + 1) + 11; // random number from 11 to 23 inclusive
cout << randomNumber;
return 0;
}
// Function definition
#include <cstdlib>
#include <ctime>
int random_int_in_range( int first, int last )
{
/* This function implements the method recommended by the knowing
* folks at comp.lang.c: http://c-faq.com/lib/randrange.html
* Returns an integer in [first, last].
*/
unsignedint N = (last - first <= RAND_MAX) /* Make sure the algorithm */
? (last - first + 1U) /* terminates by keeping N */
: (RAND_MAX + 1U); /* in rand()'s maximum range. */
unsignedint x = (RAND_MAX + 1U) / N;
unsignedint y = x * N;
unsignedint r;
do {
r = rand();
} while (r >= y);
return r / x + first;
}
#include <iomanip>
#include <iostream>
#include <map>
usingnamespace std;
int main()
{
srand( time( NULL ) );
// Let's pull 100 integers in [11, 23] from the PRNG and
// see how many of each integer we get.
map <int, int> histogram;
for (int n = 0; n < 100; n++)
histogram[ random_int_in_range( 11, 23 ) ]++;
for (auto p : histogram)
cout << p.first << " : " << setw( 2 ) << p.second << " times\n";
}