c - 如何使用函数并调用它进行简单的平均计算?

标签 c

我需要学习如何使用该函数进行计算,然后在 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/

相关文章:

创建两个以上的 StatusBar 部件

c - K & R C 变量名称

c - 编译时出现多个相同错误 "error: expected ' )' before ' *' token

c - argv[2] 值未从 cmd 正确传递

C:在 switch 中定义多维数组

c - 如何在 Linux 上检查进程的堆大小

无法理解 C 中图灵机实现的输入

c - 在C中实现管道

c - 在 C 预处理器中为其自身定义一些内容

c++ - "int a;"是 C 和 C++ 中的声明还是定义?