vector and random numbers on c++

I had some difficult to create a program who give me 10 random numbers differents from 1 - 50, using vectors. Can anyone help me? my code is giving 10 random numbers, but all the same.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <time.h>
#include <stdlib.h>
using namespace std;
int main(){
int aleatorio[10], cont;
for (aleatorio[cont] = 0; cont < 10; cont++){

srand (time(NULL));
	aleatorio[cont] = rand() % 50 + 1;
	cout << aleatorio[cont] << endl;
	
}
	
}
It should be more like this. You need to call srand only once (before the first call to rand). And you had a strange mistake in your for loop head, too.

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main(){
    srand(time(0));
    int aleatorio[10];
    for (int i = 0; i < 10; i++) {
        aleatorio[i] = rand() % 50 + 1;
        cout << aleatorio[i] << '\n';
    }
}


It isn't guaranteed that all the numbers will be different, though. If that's what you need then you either need to keep track of which values have already been chosen or shuffle an array of the values and then take the first 10.
Last edited on
Topic archived. No new replies allowed.