问题描述
如何编写一个算法,通过从用户那里接收自然数 N 来计算 e 的值?需要使用以下等式:
解决方法
我假设您想要伪代码之类的算法描述。那么你的算法可能看起来像这样:
function factorial(x)
begin
f := 1;
for i := x downto 1 do
f := f*i;
end;
factorial := f;
end;
procedure euler(n)
begin
e := 0;
for i := 1 to n do
e := e + (1/factorial(i));
end;
print e;
end.
请注意,我在这里使用了 Pascal-like pseudocode variant。这种方法也不是最快的,因为从 1 到 n 的每个阶乘都有一个额外的循环,但我选择这种方法是为了展示解决这个问题的直观方法。
,这是一个简单的java解决方案:
float result = 1;
int fact = 1;
for (int i = 2; i <= n; i++) {
fact *= i;
float fraction = 1f / fact;
result += fraction;
}