首页 > 解决方案 > 使用两个函数生成随机数数组

问题描述

我正在尝试生成一个数组,其元素是一个范围内的随机数(在最小值和最大值之间),但是出了点问题。代码就在下面。

void cria_aleatorio(int *vetor, int tamanho, int min, int max) {
    int i=0;

    for(i=0; i<tamanho; i++)
    {
        vetor[i] = (rand() % (max - min + 1)) + min;
    }
}

void print_vetor(int *vetor, int tamanho){
    printf("%d", vetor[tamanho]);
    printf("%d", tamanho);
}

标签: carrayspointersrandom

解决方案


正如评论中所指出的,您的 print_vetor 函数是错误的。您需要一个循环来遍历数组中的每个元素,就像您在生成随机数时所做的那样。

void print_vetor(int *vetor, int tamanho){
    unsigned int i = 0;
    for (i = 0; i < tamanho; i++) {
        printf("%d, ", vetor[i]);
    }
    printf("\n%d\n", tamanho);
}

推荐阅读