c - 试图在 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;
}
}
解决方案
如果您希望数字是双精度数(带小数的数字),则需要将其定义为双精度数,而不是整数。我有这段代码应该可以解决你的问题。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 的页面。
推荐阅读
- azure - 逻辑应用子文件夹触发器
- python - python中有没有像Arduino的millis()这样的函数?
- sql - oracle sql组合
- python - ValueError: s 必须是标量,或与 x 和 y 大小相同
- ios - CoreLocation - Continuous location update in background with authorizedWhenInUse authorization
- matlab - 从某些坐标之间的线轮廓计算梯度
- php - Recaptcha v2 未在 PHP 中验证
- javascript - 如何使javascript图表在HTML div中响应
- angular - core.js:6237 错误类型错误:无法设置未定义的属性“区域”
- blazor - 如何将 Blazor 组件移动到不同的程序集