Random numbers within a vector in C

Asked

Viewed 1,570 times

-1

Hello would like to know what would be the ideal method to generate random numbers within a vector in C using the function Rand(), I get an error when I try to run the code below.

follows the code:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <conio.h>

#define vMax 5

main(){
    srand(time(NULL));
    int vetor[vMax] = rand() % 10 + 1;
    for(int i = 0; i < vMax; i++){
        printf("%d",vetor[i]);
    }
}

the error basically says that the array needs to be initialized with keys but when I put the keys it tmb returns me ANOTHER error, so logically this would not be the way to generate random elements of the vector. Thank you from now on, every comment will be helping me in learning.

  • it might not be this, but try to put it like this: int vetor[vMax] = rand() % (10 + 1);

  • @Ianmoone Its solution returns error, but thanks for adding to the topic

  • Note that when you do: int vector[Vmax] = Rand() %10 + 1; you are making an assignment to the Vmax index element, however the valid indices for your vector vary from 0 to Vmax-1. You are accessing a memory position outside the area reserved for your vector.

1 answer

0


'Cause you don’t have something like that :

main(){
    srand(time(NULL));
    int vetor[vMax];
    for(int i = 0; i < vMax; i++){
        vetor[i] = rand() % 10 + 1;
    }
}
  • I didn’t think of it, but now I have repeated elements, how would I solve it?

  • When I did jobs like this in college I would go through the whole vector checking if X value had not already been added, if yes, generating another value, if not, adding it to the vector’s I position. I know, coarse solution rsrsrs

Browser other questions tagged

You are not signed in. Login or sign up in order to post.