1

我试图创建一个计算 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

4

1 回答 1

2

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

您不需要为它编写 for 循环和其他复杂的代码。下面的代码应该可以。

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;
}
于 2013-02-05T18:42:22.010 回答