0

这个 C 程序应该计算到某个点的欧拉数。只要相差 1/(n-1) 就会计算!- 1/n!小于用户输入的数字。

问题:无论我输入什么数字,欧拉数都是 2.000000。

我认为这是因为它在第一次之后离开了 do while 循环,我认为这是因为 1 - 1 等于 0,因此它小于用户输入的数字,我已经尝试通过添加条件 eul 来阻止它== 2,但是当我在这种情况下运行程序时,它根本不起作用。

这是我的程序:

#include <stdio.h>

float scanningTheDifference();
float calculatingTheEuclidianNumber(float d);
int calculatingFaculty(int i, int z);

void main () {
    char answer;
    float d;
    double eul;
    printf ("calculating the euclidian number\n");

    do {
        d = scanningTheDifference(); 
        eucl = calculatingTheEuclidianNumber(d);

        printf ("\n the euclidian number is: %lf", eucl);

        do {
            printf("\n \n do you want to repeat? (j/n)");
            fflush(stdin);
            scanf("%c", &answer);
        } while (answer != 'y' && answer != 'n');
    } while (answer == 'y');
}

float scanningTheDifference() {
    float d;                   //difference
    
    do {
        printf("\n please enter the difference of two numbers, it has to be positive: ");
        scanf("%f", &d);
    } while (d < 0);

    return d;
}

float calculatingTheEuclidianNumber(float d) {
    double num1, num2;
    double eucl = 0.0;
    int i = 1;
    int z = 1;

    do {
        num1 = 1 / i;
        i = calculatingFaculty(i, z);
        z++;
        num2 = 1 / i;
        i = calculatingFaculty(i, z);
        z++;
        eucl = eucl + num1 + num2;
    } while (num1 - num2 < d);

    return eucl;
}

int calculatingFaculty(int i, int z) {
    int res;

    res = i * z;

    return res;
}
4

2 回答 2

1

您正在尝试计算欧拉数 (2.718...) 的近似值。(这与 Euclid 无关。)您要使用的公式是:

e = sum(n=0->inf) {1/n!}

之前的评论提到了一些错误。但是,您的教师计算是错误的。可以使用递归计算教师:

int calculatingFaculty(int n) {
    return n < 2 ? 1 : n * faculty(n-1);
}

您可能应该更改终止条件,以便只要两项之间的差异大于输入的值,它就会循环因为我假设如果总和有机会收敛,差异会越来越小。 .

于 2022-02-16T14:52:16.760 回答
1

请注意,C 中整数之间的数学运算会产生整数。

num1 = 1 / i;

1除以除0(显然有问题)或1将导致0.

您可能希望在此操作中i转换为 afloat或。double

num = 1 / (float)i;

if num1and num2are both 0, then eucl = eucl + num1 + num2;is真的只是eucl = eucl;

于 2022-02-05T16:29:55.970 回答