Generating random numbers

im super new to C++ and i would like to know how i can write a program that accepts an integer number from a user say N and generates N random numbers from 0 to 1. Thank you guys
Well to get the N random numbers you will need a for loop, and I presume you already know how to request and receive input from a user so I'll leave it at that.

To get a random number use the rand() function. It should be in the cstdlib.

to get that number between 0 and 1 I would suggest using the following

variable=rand()%2;
It might be a good idea to seed the random generator with the time() function before you use the function to make it even more random. Unfortunately I can't explain the time() function to you, but I can explain the srand() (seed rand) function. The srand() function takes the number you give it in the parameter and replaces something in the rand() function with it (I honestly don't know what it replaces). If you don't do that, you'll get the same pattern of 1's and 0's every time you run the program.

1
2
3
4
5
6
7
8
9
#include <cstdlib>
#include <ctime>

int main()
{
       srand(time(0));
       
       cout << rand() % 2 << endl;
}


I don't think I really explained that good, so you should look at these links: http://cplusplus.com/reference/clibrary/ctime/time/, and http://cplusplus.com/reference/clibrary/cstdlib/srand/.
i tried using variable = rand () %2, it didnt work it generated only 0's and 1'2, but i need numbers like 0.34, 0.45,0.67..thanks
If you only want decimals to the hundredth place, you can do this:

1
2
3
4
int main()
{
      (rand() % 100 + 1) / 100;
}


The plus 1 is so it'll be a random number from 1 to 100 rather than 0 to 99. Make sure that variable is a float or double (data values with decimal points), or else you'll still just get 1's and 0's.
Even so, one of the operands of the division must be a floating point number. So divide by 100.0 instead.
Oops, I forgot. Do what he said.
Topic archived. No new replies allowed.