这会在数组中生成阱槽(例如arr [0] = 753,[1] = 324,[2] = 876)
int main(void){
// Introducing the 'n' number, the max number in the array
int num;
cout << "Introduce the quantity of random numbers between 100 and 999\nNumber: "; cin >> num;
int arr[num];
// Generating random numbers for the i's slots in the array
srand(time(0));
// Filling the array
for(int i = 0; i < num; i++)
arr[i] = (rand() % 900) + 100;
// Printing the array
for(int i = 0; i < num; i++)
printf("item [%i] = %i\n", i, arr[i]);}
但是这会产生类似arr [0] = 9,[1] = 425345,[2] = 0,[3] = 324,[4] = 48,[5] = 232424 但是当我把n> = 8时,从1到7有效,而当8或更高时,则不起作用
void randomArray(int size)
{
int arr[size];
// Generating random numbers for the i's slots in the array
srand(time(0));
for(int i = 0; i < size; i++)
arr[i] = (rand() % 900) + 100;
}
void printArray(int size)
{
int arr[size];
for(int i = 0; i < size; i++)
printf("item [%i] = %i\n", i, arr[i]);
}
int main(void)
{
// Introducing the 'n' number, the max number in the array
int num;
cout << "Introduce the quantity of random numbers between 100 and 999\nNumber: "; cin >> num;
int arr[num];
srand(time(0));
// Filling the array
randomArray(num);
// Printing the array
printArray(num);}
答案 0 :(得分:1)
您没有使用在main方法中声明的与数组相同的数组来保存随机数。您可以查看更多here。尝试使用printArray(int size, int* arr)
和randomArray(int size, int* arr)
,不要在方法中声明数组,而将其与randomArray(num,arr)
和printArray(num,arr)
配合使用可以解决您的问题。