首页 > 解决方案 > 试图在 C 中逼近欧拉数

问题描述

我正在尝试使用公式来近似欧拉数(1+(1/n))^n。编译器告诉我有一个“'double'之前的预期表达式”这是代码:

#include <stdio.h>
#include <math.h>

int main()
{
    int x, y, power;
    int num = 1;
    int position = 1;
    while (position <= 100)
    {
        num = 1/num;
        num = num + 1;
        x = num;
        power = double pow(x, x); //here
        printf("%f", power);
        position += 1;
        num = position;
    }
}

标签: cfunctionpowmath.h

解决方案


如果您希望数字是双精度数(带小数的数字),则需要将其定义为双精度数,而不是整数。我有这段代码应该可以解决你的问题。gcc FILEPATH -lm -o OUTPUTPATH如果您使用的是 UNIX,还要确保进行编译。

#include <stdio.h>
#include <math.h>

int main()
{
    double x, y, power, num = 1; //doubles allow for decimal places so declare it as double
    int position = 1; //Position seems to only be an integer, so declare it as an int.
    while (position <= 100)
    {
        num = 1/num;
        num++;
        x = num;
        power = pow(x, x);
        printf("%f", power);
        position += 1;
        num = position;
    }
}

另一种选择是 for 循环:

#include <stdio.h>
#include <math.h>

int main()
{
    double x, y, power, num = 1;
    for (int i = 1; i <= 100; i++) {
        num = 1/num;
        num = num + 1;
        x = num;
        power = pow(x, x);
        printf("%f", power);
        position += 1;
        num = i;
    }
}

如果您想近似欧拉数,我不明白为什么不尝试以下方法:

static const double E = 2.718281828459045;

我只是更正了您程序中的语法错误,但我认为它实际上不会为您提供 E。请参阅有关在 C 中计算 E 的页面。


推荐阅读