2
這段程式碼是用來算
e^x = 1 + x + x^2 / 2! + x^3 / 3! + ......
今天只讓該程式算到 x^15 / 15! 而已
x 用 5 代入
不過執行下去的結果是 nan
完全不知道問題在哪裡
Fact function 是階乘 recursion
Exp function 是指數 recursion
Sum function 是用來累算 1 + x^2 / 2! + x^3 / 3! + ...... + x^15 / 15!
目前每個 Function debug 後
Fact 和 Exp 的結果都沒問題
8 # include <stdio.h>
9
10 double Fact ( double num ) {
11
12 if( num <= 1 ) return 1;
13
14 else return num * Fact( num-1 );
15
16 } // float Fact()
17
18 double Exp ( double base, double power ) {
19
20 if ( power > 0 )
21 return base*Exp( base, power-1 );
22
23 else return 1;
24
25 } // float Exp()
26
27 double Sum ( double sum, double x, double max ) {
28
29 max++;
30
31 sum = sum + Exp( x, max ) / Fact( max );
32
33 if ( max < 15 ) // 當 Sum 算到 max 為 15 後就停止
34 Sum ( sum, x, max );
35
36 else return sum;
37
38 } // float Sum()
39
40 main() {
41
42 double x = 5, max = 0, sum = 1;
43
44 printf( "%f\n", Sum( sum, x, max ) );
45
46 } // main()
P.S. 有規定禁止使用 exp(x)
後來發現到 Sum 的 34 行忘記加 return
另外 Sum 本身邏輯出現錯誤......
Update: 問題已自行解決