轉載自:https://blog.csdn.net/xia0liang/article/details/53157455
【程序24】
題目:有一分數序列:2/1,3/2,5/3,8/5,13/8,21/13...求出這個數列的前20項之和。
1.程序分析:請抓住分子與分母的變化規律。
2.程序源代碼:
#include "stdio.h"
#include "stdlib.h"
//#include <windows.h>
int main()
{
//SetConsoleOutputCP(437);
int n, t, number = 20;
float a = 2, b = 1, s = 0;
for (n = 1; n <= number; n++)
{
s = s + a / b;
t = a; a = a + b; b = t;
}
printf("sum is %9.6f\n", s);
system("pause");
}
【程序25】
題目:求1+2!+3!+...+20!的和
1.程序分析:此程序只是把累加變成了累乘。
2.程序源代碼:
#include "stdio.h"
#include "stdlib.h"
//#include <windows.h>
int main()
{
//SetConsoleOutputCP(437);
float n, s = 0, t = 1;
for (n = 1; n <= 20; n++)
{
t = t*n;
s = s + t;
}
printf("1+2!+3!+...+20!=%e\n", s);
system("pause");
}
【程序26】
題目:利用遞歸方法求5!。
1.程序分析:遞歸公式:fn=fn_1*4!
2.程序源代碼:
#include "stdio.h"
#include "stdlib.h"
//#include <windows.h>
int fact(int j)
{
int sum;
if (j == 0)
sum = 1;
else
sum = j*fact(j - 1);
return sum;
}
int main()
{
//SetConsoleOutputCP(437);
int i;
scanf("%d", &i);
printf("%d!=%d\n", i,fact(i));
system("pause");
}