我需要函数 drop_balls 来返回一个数组,以便我可以让我的下一个函数使用该数组。我需要它接受一个整数作为参数,然后返回一个 int 数组,以便它可以用于我将在之后制作的另一个函数中。我一直在阅读它只能作为指针传递,但我完全不知道它是如何编码的,有人可以帮助我。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/* Prototype for drop_Balls, int parameter is number of balls being dropped */
int [] drop_balls(int);
/* Gets the number of balls that need to be dropped by the user */
int get_num_balls();
int main()
{
drop_balls(get_num_balls());
}
int get_num_balls()
{
int num_balls;
printf("How many balls should be dropped? ");
scanf("%d", &num_balls);
/* Ensure that it is atleast one ball */
while(num_balls <= 0)
{
printf("You have to drop at least one ball! \n ");
printf("How many balls should be dropped? ");
scanf("%d", &num_balls);
}
/* Return the number of balls that will be dropped */
return num_balls;
}
int [] drop_balls(int num_balls)
{
/* Keeps track of how many balls landed where */
int ball_count[21];
/* What number ball are we on */
int ball_num = 0;
/* Seed the generator */
srand(time(NULL));
/* Do the correct # of balls */
for(ball_num = 0; ball_num < num_balls; ball_num++ )
{
/* Start at 10 since its the middle of 21 */
int starting_point = 10;
/* Bounce each ball 10 times */
for(starting_point = 10; starting_point > 0; starting_point--)
{
int number;
/* Create a random integer between 1-100 */
number = rand() % 100;
/* If its less than 50 bounce to the right once */
if(number >= 50)
{
starting_point++;
}
/* If its greater than 50, bounce to the left once */
else
{
starting_point--;
}
}
/* Add one to simulate one ball landing there */
ball_count[starting_point]++;
}
return ball_count;
}