【问题标题】:Generating an array of random numbers using two functions [closed]使用两个函数生成随机数数组[关闭]
【发布时间】:2018-11-08 13:45:30
【问题描述】:

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

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);
}

【问题讨论】:

  • 出了什么问题?
  • 寻求调试帮助的问题(“为什么这段代码不起作用?”)必须包括所需的行为、特定的问题或错误以及在问题本身中重现它所需的最短代码。没有明确问题陈述的问题对其他读者没有用处。请参阅:如何创建最小、完整和可验证的示例。
  • 其余代码在哪里?你有“两个功能”,但只有一个是关于随机数的。
  • 你将 vetor 从 0 填充到 tamanho-1,然后请求 vetor[tamanho],它超过了数组的末尾。
  • 这可能不一样tamanho,它可能是从循环中调用的。我们不知道。

标签: c arrays pointers random


【解决方案1】:

正如 cmets 中所指出的,您的 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);
}

【讨论】:

  • 正是我准备好的!。
  • @WeatherVane 思想相通!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-03-22
  • 1970-01-01
  • 2014-11-17
  • 2016-09-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多