-1
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;


void seedRandom()
{
  srand(time(NULL));
}

double nextRandom()
{
  seedRandom();
  double ran;
  ran = ( (double) rand()) / RAND_MAX;
  cout << ran;
  return ran;
}

int main()
{
    cout<<nextRandom;
}

Why does this print 1 every time and not a random number between 0 and 1? I looked everywhere but it does not seem to work. This is due at midnight. Also, this is only an excerpt from a long code.

  • It's a bad idea to div by RAND_MAX for customizing rand() range. Why don't you use std::mt19937, std::random_device and std::uniform_real_distribution? – yumetodo Oct 12 '19 at 01:37
  • On top of the answer get `seedRandom();` out of `nextRandom`. Instead call `seedRandom()` 1 time in main. – drescherjm Oct 12 '19 at 01:44
  • do not put `srand` inside a function, it's supposed to be called only once at startup [srand() — why call it only once?](https://stackoverflow.com/q/7343833/995714) – phuclv Oct 12 '19 at 02:57

2 Answers2

4
cout<<nextRandom;

This does not call your nextRandom function. The right argument to << is a pointer to the function, not the result of calling it. In this context, if I'm not mistaken, the pointer value is implicitly converted to bool, yielding true (1) if the pointer is not null -- which it never will be.

Add empty parentheses to call the function.

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
  • [Why std::cout << main << std::endl prints 1? (duplicate)](https://stackoverflow.com/q/28660352/995714), [Why pointer to function is equal to 1? (duplicate)](https://stackoverflow.com/q/53129402/995714), [why is the address of a c++ function always True?](https://stackoverflow.com/q/6022881/995714) – phuclv Oct 12 '19 at 03:00
4

I think there are several problems with your codes

  • In main function, you should use nextRandom() as a function call instead of print function itself.
  • You should seedRandom once only at the beginning instead of run it every time, because time function return seconds, so if you call nextRandom() multiple times inside a second, you might get the same random number.
  • After C++11, you probably should consider use <random> library in C++ to generate random number with the range.

Here is the simple example as reference

double nextRandom()
{
  thread_local std::random_device rd;
  thread_local std::mt19937 gen(rd());
  std::uniform_real_distribution <> dist(0.0, 1.0);
  return dist(gen);
}
2power10
  • 1,259
  • 1
  • 11
  • 33