mardi 11 février 2020

Why is rand giving me almost identical (but slightly different) numbers each time

I wrote the following piece of code to generate random numbers in c++

#include <stdlib.h>
#include <iostream>
#include <ctime>

#define ARRAY_SIZE 5
#define MAX_VAL ARRAY_SIZE*5+1

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

  int arr [ARRAY_SIZE];
  for (int i = 0; i < ARRAY_SIZE; i++) {
    arr[i] = (rand() % MAX_VAL);
  }

  for (int i = 0; i < ARRAY_SIZE; i++) {
    printf ("%d\n", arr[i]);
  }

  return 0;
}

When I run this I get almost identical numbers each time:

tyler@Tylers-MacBook-Pro hw2 % ./MergeSort
11
16
16
21
16
tyler@Tylers-MacBook-Pro hw2 % ./MergeSort
21
11
21
11
6
tyler@Tylers-MacBook-Pro hw2 % ./MergeSort
6
6
1
16
6
tyler@Tylers-MacBook-Pro hw2 % ./MergeSort
16
1
16
6
21
tyler@Tylers-MacBook-Pro hw2 % ./MergeSort
1
21
21
11
21
tyler@Tylers-MacBook-Pro hw2 % ./MergeSort
1
21
21
11
21
tyler@Tylers-MacBook-Pro hw2 % ./MergeSort
11
16
1
1
11
tyler@Tylers-MacBook-Pro hw2 % ./MergeSort
11
16
1
1
11
tyler@Tylers-MacBook-Pro hw2 % ./MergeSort
21
1
6
6
1

Why is my random number generator only giving me the values: 1, 6, 11, 16 and 21? This makes no sense to me. I made sure to seed it and the numbers aren't always in the same order which is what makes this even more confusing. As a side note I am using OSX.




Aucun commentaire:

Enregistrer un commentaire