Generating random numbers

1
2
3
4
5
for (int i=0; i<15; i++)
    {
        nx[i]=rand()%8+1;
        printf("%d",nx[i]);
    }


I want to the function of timer "srand(time(NULL))" to generate seed for random numbers.
By running this for loop,I think I should expect random numbers ranging from 1 to 8.However, I get some wried numbers from the console window like 88,044,077,066,088,088,066,022,044,044,088,022,033,66814990522,-156026525933,1606416712. One more thing,I think I am going to have 15 outputs, but why I get 16 instead every time.

Can anyone help me with that?
The snippet of code you posted works OK for me after adding in a few more lines. Do you have the array defined differently?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <cstdlib>
#include <ctime>
#include <cstdio>

int main()
{
    int nx[15];
    srand(time(NULL));
    
    for (int i=0; i<15; i++)
    {
        nx[i]=rand()%8+1;
        printf("%d",nx[i]);
    }
244735833846811 

Last edited on
Topic archived. No new replies allowed.