我需要学习如何使用该函数进行计算,然后在 main 中进行简单的调用。当我尝试时它不起作用。我不知道该怎么做。它有效,但是当我从 main 中取出代码时,它变得很奇怪。 这是简单的场景和代码。
编写一个函数,它接受一个整数数组和该数组的大小 - 另一个整数。
它还返回一个 double 值。称此为“平均”。返回一个 double 值,即平均值
数组中的值。通过求数组的平均值来证明它的工作原理
值为 {78, 90, 56, 99, 88, 68, 92}
#include <stdio.h>
#include <stdlib.h>
// Outside of main, a function will be declared that takes an array of ints.
double Function(int Array[7])
{
// int Array[7] = {78, 90, 56, 99, 88, 68, 92};
int sum = 0;
int i;
double average;
// This for loop allows us to use all 7 elements in the array.
for(i=0; i<7; i++)
{
// This takes all the array's elements and sums them up.
sum += Array[i];
}
// This prints the sum
printf("Sum = %d\n", sum);
// The double average is found by taking the sum found and dividing it by 7.
average = sum/7;
// This prints the average in a double.
printf("The resulting average is %lf \n", average);
return average;
} // Ends Function
// There will also be the size of the array(which is another int)
// The function will return a double called average. It is the average of the values in the array.
int main()
{
//int i; // Allows us to use the for loop and print each element in the corresponding array.
// int array numbers are declared and initialized.
int Array[7] = {78, 90, 56, 99, 88, 68, 92};
int sum = 0;
int i;
double average;
// This for loop allows us to use all 7 elements in the array.
for(i=0; i<7; i++)
{
// This takes all the array's elements and sums them up.
sum += Array[i];
}
// This prints the sum
printf("Sum = %d\n", sum);
// The double average is found by taking the sum found and dividing it by 7.
average = sum/7;
// This prints the average in a double.
printf("The resulting average is %lf \n", average);
Function(Array);
system("pause");
return 0;
}
谁能给我一点建议吗?
最佳答案
如果您想遵循给定的说明,您的函数声明应该是
double average(int *array, int array_size)
此外,您的解决方案应该是通用的,而不仅仅是长度为 7 的数组。
一般来说,在 C 语言中 - 当您想要传递长度未知的数组时,您可以传递数组的地址(此处 *array
)及其大小(此处 array_size
)。然后你的函数将从给定地址迭代数组,并跳转类型(这里跳转 sizeof(int)
因为它是一个整数数组)。
关于c - 如何使用函数并调用它进行简单的平均计算?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43197158/