2

I'm trying to write a program that uses a function to generate 10 random numbers within a range provided by the user. It seems to work okay, other than the fact that the numbers returned are all 1's:

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int rand_int(int min, int max);

int main()
{
    int min, max;

    cout << "Hello user.\n\n"
         << "This program will generate a list of 10 random numbers within a 
         given range.\n"
         << "Please enter a number for the low end of the range: ";
    cin  >> min;
    cout << "You entered " << min << ". \n"
         << "Now please enter a number for the high end of the range: ";
    cin  >> max;

    while(min > max){
        cout << "Error: Your low number is higher than your high number.\n"
             << "Please reenter your high number, or press ctrl + c 
                 to end program.\n";
        cin  >> max;
        cout << endl;
    }

    for(int i = 0; i < 10; i++){
        int rand_int(int min, int max);
        cout << rand_int << endl;
    }

    return 0;
}


int rand_int(int min, int max)
{
    srand(time(0)); // Ensures rand will generate different numbers at different times

    int range = max - min;

    int num = rand() % (range + min);

    return num;
}
Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
Bobby
  • 37
  • 1
  • 3
  • 6
  • 1
    You should go back and read up on variable definition and functions calls. Also, don't reseed everytime (especially not with `time(0)` in a tight loop). – jerry Feb 02 '14 at 03:11
  • Can you be a little more specific? I have the book right in front of me and it doesn't get very specific on where or how you can call them. – Bobby Feb 02 '14 at 03:12
  • Try stepping through the code with a debugger, and if you don't have one add prints to the code to show you what is happening. – brian beuning Feb 02 '14 at 03:15
  • This looks like a homework problem, but I think you will find it enlightening to use a debugger to step thru the rand_int function. I'd break up the `int num = rand() % (range + min);` line so you can see what is going on in there. (Great minds must think alike @brianbeuning) – boatcoder Feb 02 '14 at 03:15
  • This following link got the same issue: http://stackoverflow.com/questions/9484588/c-generating-random-numbers – Emu Feb 02 '14 at 03:18
  • @Emu same symptoms, totally different causes. – jerry Feb 02 '14 at 03:28
  • 1
    This has been explained [countless times on SO](http://stackoverflow.com/questions/288739/generate-random-numbers-uniformly-over-an-entire-range?rq=1), but do not use modulo arithmetic to restrict the range of output from an RNG. You will skew the distribution of results. Also, seeding the RNG with `time (0)` is not going to do you any favors - `time (0)` has a 1 second granularity. You are basically re-seeding the RNG with the same value if you call `rand_int (...)` frequently. – Andon M. Coleman Feb 02 '14 at 03:45
  • The line "int rand_int(int min, int max);" is not the correct way to call a function. – drescherjm Feb 02 '14 at 03:47
  • Put the seeing into your main. Call it 1 time. Don't seed in a loop. – drescherjm Feb 02 '14 at 03:52
  • See here for uniform distribution: http://stackoverflow.com/questions/4195958/how-do-i-scale-down-numbers-from-rand and here for why rand is bad: http://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful – Brandon Feb 02 '14 at 03:57

3 Answers3

4

Having warnings turned on may have helped here, with -Wall flag gcc tells us:

warning: the address of 'int rand_int(int, int)' will always evaluate as 'true' [-Waddress]
     cout << rand_int << endl;
             ^

Although clang gives a warning without the need to add flags. You are using a function pointer here and since std::cout does not have an overload for a function pointer it is selecting the bool overload and converting the function pointer to true. The calls should be like this:

std::cout << rand_int(min, max)  <<std::endl;

Although that will not totally fix your issues, you also need to move:

srand(time(0));

outside your function preferably at the start of your program. Since you are calling rand_int ten times very quickly the result of time(0) will probably be the same and therefore you will return the same 10 numbers.

This line:

int rand_int(int min, int max);

in the for loop is just a redeclaration of the function and is not needed.

Although, if C++11 is an option using the random header makes way more sense and is much simpler:

#include <iostream>
#include <random>

int main()
{
    std::random_device rd;

    std::mt19937 e2(rd());

    std::uniform_int_distribution<int> dist(1,10);

    for (int n = 0; n < 10; ++n) {
            std::cout << dist(e2) << ", " ;
    }
    std::cout << std::endl ;
}

If C++11 is not an option then your should at least check out the How can I get random integers in a certain range? C FAQ entry which gives the following formula for generating numbers in the range [M, N]:

M + rand() / (RAND_MAX / (N - M + 1) + 1)

and of course there is always boost:

#include <iostream>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_int_distribution.hpp>

int main()
{
  boost::random::mt19937 gen;
  boost::random::uniform_int_distribution<> dist(1, 10);

  for (int n = 0; n < 10; ++n) {
    std::cout << dist(gen) << ", ";
  }
  std::cout << std::endl ;
}
Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
0

Try changing this:

for(int i = 0; i < 10; i++){
    int rand_int(int min, int max);
    cout << rand_int << endl;
}

to:

for(int i = 0; i < 10; i++){
    int myRandomNumber = rand_int(int min, int max);
    cout << myRandomNumber << endl;
}

It seems that you were outputting the function rather than the return result of it.

rhughes
  • 9,257
  • 11
  • 59
  • 87
  • Thanks for the response, I have to go with the rand method because its for an assignment. I keep getting a parse error on the first line of the for-loop body. "Parse error before ',' " – Bobby Feb 02 '14 at 03:40
  • @Bobby OK. Focus on the first part of my answer. I have removed the unnecessary part. – rhughes Feb 02 '14 at 03:41
0

The Fastest & Simplest way to get the Random Number within a range is-

int lower=1,upper=10;//for example
srand(time(0));
int y = (rand() % (upper-lower + 1)) + lower;

It will give you the output in the range- [1,10] (both inclusion).

That's it. Cheers!

Yash
  • 1,787
  • 1
  • 22
  • 23