-3

i want to create a random number between 0 and 1 but my codes output is zero.

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main()
{
  srand(time(0));

  for(int x=0;x<100;x++)
  {
      cout<<(rand()%10)/10<<endl;
  }
  return 0;
}
Rowland Shaw
  • 37,700
  • 14
  • 97
  • 166

2 Answers2

4

This: (rand()%10)/10 gives you a (low quality) random integer between zero and RAND_MAX, then you use modulo to turn that into a (biased) integer between zero and nine, then you perform integer division by 10 which will always be a value less than 1 which will be truncated to zero.

A much better solution would be to use the random facilities from C++11 and use a std::uniform_real_distribution to obtain your value between 0 and 1.

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70
0

You are dividing an int. Anything lower than one will be cut to 0. You need to declare/cast a double or float (to have decimals).

Carele
  • 756
  • 3
  • 13
  • 2
    No - even casting to float or double won't give you an uniform distributed random number between 0 and 1 – jhilmer Jan 31 '17 at 15:24
  • 1
    @jhilmer I only answered part of the question (why the output is 0). Actually there is not actual question to begin with so i did just give him a hint to try and correct his code. I should have added that this is not the solution to the whole problem. – Carele Jan 31 '17 at 15:30