【发布时间】:2019-12-04 14:41:47
【问题描述】:
我对整体编程有点陌生,目前正在用 C 编程,我目前正在开发一个程序,该程序首先将 10 个数字随机化,放入一个数组中并将它们打印在屏幕上,然后让用户输入一个整数,然后程序应该检查数组并打印出用户输入的整数在数组中出现了多少次,这就是我遇到问题的地方。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// Function to initialize random numbers.
int Random()
{
srand(time(NULL)); // To initialize the random number generator.
return 0; // Really only the important part from the function, that it returns something.
}
// Generates randome values for the array.
void setRandomNumber(int inputArray[], int arraySize)
{
int i;
Random(); // Calls the "Random" function.
for(i = 0; i < arraySize; i++) // Conditions for when/how many times to run the loop.
inputArray[i] = (rand() % 10) + 1; // What values the array will get, random numbers between 1 and 10.
}
// Function to count the occurrances of an element.
int countElement(int inputArray[], int arraySize, int elementCount)
{
}
int main(void)
{
int numbers[10];
int loop;
int run = 1;
int elementCount = 1;
setRandomNumber(numbers, 10); // Calls the "setRandomNumber" fucntion to set random values to the floats in the array.
countElement(numbers, 10, elementCount);
for (loop = 0; loop < 10; loop++) // Prints out the already randomized values of the array "numbers"
printf("Number: %d\n", numbers[loop]);
printf("\nWhat to search for: ");
scanf_s("%d", &elementCount); // Takes user input on what number to check.
printf("The number %d occurs %d times.\n", elementCount, countElement);
return 0;
}
我们需要使用函数,并且函数头必须看起来像 int countElement(int inputArray[], int arraySize, int elementCount),在这种情况下,我遇到问题的是 countElement 函数。
【问题讨论】:
-
有什么问题?您是否尝试过编写
countElement函数? -
您遇到的一个主要问题是在
printf("The number %d occurs %d times.\n", elementCount, countElement);行中 - 您所拥有的最后一个参数将是countElement函数的地址。要获取函数的返回值,您需要使用参数指定函数,如下所示:countElement(numbers, 10, elementCount).
标签: c arrays function element find-occurrences