引入
展開式求和:輸入 1 個實數 x,計算並輸出下式的值,直到最後一項的絕對 值小於 0.00001,計算結果保留 2 位小數。要求定義和調用函數 fact(n)計算 n 的階乘,可以調用 pow( )函數求冪。試編寫相應程序。 s=x+x²/2!+x³/3!+x4/4!+…
分析
fact()求階層,需要注意返回值和自變量的初始化
結束條件 item >= 1e-5
item的值根據pow(x,i)/fact(i)求
代碼
#include <stdio.h>
#include <math.h>
//聲明階層函數
double fact(int x);
int main(void) {
/**
展開式求和:輸入 1 個實數 x,計算並輸出下式的值,直到最後一項的絕對 值小於 0.00001,
計算結果保留 2 位小數。要求定義和調用函數 fact(n)計算 n 的階乘,可以調用 pow( )函數求冪。
試編寫相應程序。 s=x+x2/2!+x3/3!+x4/4!+…
*/
//輸入一個實數
double x;
scanf("%lf",&x);
//定義項、和、自變量
double s,item = 1.0;
int i = 1;
while(fabs(item) >= 1e-5){
//調用pow()和fact()求每項的值
item = pow(x,i)/fact(i);
s+=item;
i++;
}
//打印和
printf("s=%.2lf",s);
return 0;
}
//求階乘
double fact(int n){
int i;
double result = 1;
for(i = 1; i <= n; i++){
result=result*i;
}
return result;
}