我試圖計算涉及階乘的系列之和。
系列是:1 1/2! 1/3! 1/4! ...
順便說一句 3!= 1 x 2 x 3
4!= 1 x 2 x 3 x 4
...依此類推,每個數字都像這樣繼續
這是我為運行 C 程式而撰寫的代碼:
#include <stdio.h>
void main() {
/* Any problems with the variables? */
int i, lim, fact = 1;
float sum = 0.0, term;
printf("Enter the limit for the sum of series: ");
scanf("%d", &lim);
/* Any problems in the loop? */
for (i = 1; i <= lim; i ) {
fact *= i;
term = 1 / fact;
sum = fact;
}
printf ("%f is the sum of the series\n", sum);
}
這里是否有任何我看不到的語法錯誤,或者是編譯器的問題。如果是這樣,我在 ubuntu 上使用 gcc。不過,我沒有得到正確的輸出。
uj5u.com熱心網友回復:
至少有這些問題:
1 / fact是int除以int商。
嘗試除法和1.0f / fact商。floatfloat
sum = fact;-->sum = term;是代碼應該總結條款。
uj5u.com熱心網友回復:
您的代碼中有一些錯誤。
第一個,在我們開始學習C的時候很常見
1 / fact必須替換為1.0f / fact
為什么?因為在 C 中,1 / 2使用整數算術執行并回傳0. 如果要使用浮點數執行計算,則必須強制至少一個引數為浮點數,這可以通過1.0/2或1/2.0來完成1.0/2.0。前面的運算式將使用double浮點數型別(這是浮點數的 C 默認型別)進行評估。如果你想使用簡單的精度浮點數float,你可以使用1.0f
第二個肯定是無意的錯誤:
sum = fact;必須替換為sum = term;
這是一個“作業”代碼
#include <stdio.h>
void
main()
{
/*Any problems with the variables ?*/
int i, lim, fact = 1;
float sum = 0.0, term;
printf("Enter the limit for the sum of series: ");
scanf("%d", &lim);
/*Any problems in the loop ? */
for (i = 1; i <= lim; i )
{
fact *= i;
term = 1. / fact; /* instead of 1/fact */
sum = term; /* instead of sum = fact */
}
printf("%f is the sum of the series\n", sum);
}
輸入系列和的限制:5
1.716667 是系列的總和
There is a more subtle error. By instance, if you want lim = 50,
Enter the limit for the sum of series: 50
inf is the sum of the series
The reason is that 50! is way too big to be stored in an int.
The solution is to compute directly 1/i! using floating number (and not i! using int then 1/i!)
A modified program, that also uses double for an higher precision is :
#include <stdio.h>
void
main()
{
/*Any problems with the variables ?*/
int lim;
double sum = 0.0, term = 1.0;
printf("Enter the limit for the sum of series: ");
scanf("%d", &lim);
/*Any problems in the loop ? */
for (int i = 1; i <= lim; i )
{
term = term / i;
sum = term;
}
printf("%f is the sum of the series\n", sum);
}
that now works, even when lim=50
Do not be discouraged by these mistakes. These are mistakes we all made when we learned C !
Expected result:
exp(1) = exp(0) sum_{i=1}^\infty 1/i!
thus your expected result is exp(1)-exp(0) = 1.718281828459045....
uj5u.com熱心網友回復:
用 int main() 嘗試一次,讓我知道它是否有效
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/455293.html
