我试图让一个数组在一个函数中被初始化。按预期工作时,初始化数组应包含一组在一定范围内的随机数。这在 C 中可能吗?
最佳答案
#include <time.h> //time func for seed init
#include <stdlib.h> //srand/rand funcs
#include <stdio.h> //Library for printf function
#define LIMIT 100
void myFunction(int array[], int arrayIndexMaxSize){
for (int index = 0; index < arrayIndexMaxSize; index++){
array[index] = rand() % LIMIT; //Where limit is randomly produced from 0 - Limit inclusive
printf("array[%d] of arrayIndexMaxSize(%d) = %d\n", index, arrayIndexMaxSize, array[index]); //prints out th$
}
}
void main(){
srand(time(0)); //initializes kinda random number generator
int array[50]; //If known at runtime or compile time, must be at block scope meaing inside {curly} braces of any$
myFunction(array, 50);
}
关于c - 使用函数初始化数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58421408/