It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center。
7年前关闭。
我写了这段代码。我认为可以,但是运行它时,我会得到不好的结果。该代码用于计算欧拉数。感谢您的回答。
我期望的结果约为2.718281828459045,并获得结果2.718281745910644:
2.718281828459045(预期)
2.718281745910644(实际)
码:
如果
您的计算给您的(相对较小)错误是由于对
我们将
并将其转换为
您得到的值是:
最接近期望结果的
7年前关闭。
我写了这段代码。我认为可以,但是运行它时,我会得到不好的结果。该代码用于计算欧拉数。感谢您的回答。
我期望的结果约为2.718281828459045,并获得结果2.718281745910644:
2.718281828459045(预期)
2.718281745910644(实际)
码:
#include <stdio.h>
main() {
int factor, counter, n = 1;
float total = 0, division;
while ( n <= 20 ) {
counter = 1;
factor = n;
while ( counter < n ) {
factor *= ( n - counter );
counter++;
}
division = 1.0 / factor;
total = total + division;
n++;
}
total = total + 1;
printf( "La constante matematica e vale aproximadamente: %.20f\n", total);
return 0;
} /* Finaliza funcion main */
最佳答案
while ( n <= 20 ) {
contador = 1;
factorial = n;
while ( contador < n ) {
factorial *= ( n - contador );
contador++;
}
// snip
n++;
int
,如果是32位整数类型,则最多只能保存12!
的阶乘。 13! = 6227020800
对于32位整数太大。这样就产生了溢出,结果是完全错误的。如果
factorial
是double
或64位整数而不是int
,则可能会获得较好的结果。您的计算给您的(相对较小)错误是由于对
float
和double
使用total
而不是division
引起的:我们将
e
近似为double
Prelude Text.FShow.RealFloat> FD $ exp 1
2.718281828459045090795598298427648842334747314453125
并将其转换为
float
:Prelude Text.FShow.RealFloat> FF $ realToFrac it
2.71828174591064453125
您得到的值是:
2.718281745910644
对打印的不同精度取模。与将exp 1
计算为浮点数时得到的结果相同:Prelude Text.FShow.RealFloat> FF $ exp 1
2.71828174591064453125
最接近期望结果的
float
值:Prelude Text.FShow.RealFloat> FF 2.718281828459045
2.71828174591064453125
关于c - C计算欧拉数的精度低于预期的精度,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13885182/