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