c - 尝试用 C 语言逼近欧拉数

标签 c function pow math.h

我正在尝试使用公式(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;
    }
}

最佳答案

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

#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。请参阅this page关于在 C 中计算 E。

关于c - 尝试用 C 语言逼近欧拉数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58545339/

相关文章:

c - 如何将o/p存储到缓冲区中,然后从缓冲区存储到文件

c - 在 c 中练习使用指针时得到奇怪的输出

java - 使用Math.pow在java中对数字进行平方得到精度误差

c - 使用 C 中的 POW 函数反转五位数字

java - 在 Java 中使用 pow() 方法

c - C语言中如何分别对小数点前后的数字求和?

c - 相同的功能不同的结果

javascript - this 关键字不适用于箭头函数

function - 传递给函数的 boolean 值未按预期工作

c - 找到一个精确的函数来指示算法所采取的步数