用函数计算C中2个双数的调和平均值

时间:2013-02-05 18:29:11

标签: c

我试图创建一个计算2个输入数字的函数。

当我输入例如1.05.0时,我会在输出中输入0.00

你可能会发现这个问题对你来说是非常明显的,但是我知道这是一个新手,我现在只是指点一下。

这是我的代码:

#include <stdio.h>
#define MAXNUMS 50
double harmonic_mean(double number1, double number2);

int main(void)

{
    double num1, num2;
    printf("please enter two numbers to get the harmonic mean:\n");
    while ((scanf("%lf%lf", &num1, &num2)) == 2)
    {
        printf("%.2lf", harmonic_mean(num1, num2));
    }
    return 0;
}

double harmonic_mean(double number1, double number2)

{
    double harmonic, totalHarmonic;
    int total;
    int x, y;
    double numbers[MAXNUMS];
    for (x = 1, y = 0; x <= number2; x++, y++)

    {
        total = x;
        numbers[y] = number1++;
    }

    for (x = 0; x <= total; x++)
    {
        harmonic += (1/numbers[x]);
    }

    totalHarmonic = total/harmonic;

    return totalHarmonic;
}

tnx

1 个答案:

答案 0 :(得分:2)

当你说调和均值时,不确定你到底想到了什么,但是两个数的调和平均值是它们倒数的算术平均值的倒数。

您不需要为它编写循环和其他复杂代码。以下代码应该这样做。

double harmonic_mean(double number1, double number2) {
    double r1 = 1 / number1;    // reciprocals
    double r2 = 1 / number2;

    double hm = 2 / (r1 + r2);  // reciprocal of the arithmetic mean of the two
    return hm;
}