函数计算均值

时间:2017-04-28 15:01:33

标签: arrays function loops double mean

我正在尝试使用一个带有我的数组中总双数的int数的函数计算数字的平均值,但我觉得我的功能很糟糕,有关如何改进我的功能的任何建议吗?

#include <stdio.h>

double meanOfPositive(double *arr, int length);

int main()
{
    int numValue = 6;
    double numbers[] = { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6 };
    double mean2;

    mean2 = meanOfPositive(numValue, numbers);

    printf("Mean of all numbers is %.2f", mean2);
    getchar();
    return 0;
}

double meanOfPositive(double *arr, int length)
{
    int numValue = 6;
    double tot = 0;
    double mean = 0;
    double numbers[] = { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6};

    for (int i = 0; i < numValue; i++)
    {
        tot = tot + numbers[i];
    }
    mean = tot / numValue;
    return mean;
}

1 个答案:

答案 0 :(得分:0)

我将做的是以下内容:

double mean(double arr[], int len)
{
    double total = 0;
    for(int i = 0; i < len; i++)
        total += arr[i];
    return total / len;
}

然后你就像这样从主叫它:

double mean2 = mean(numbers, numValue);