C语言:计算并输出S=1+(1+2^0.5)+(1+2^0.5+3^0.5)...+(1+2^0.5+3^0.5+...+n^0.5)

//计算并输出S=1+(1+2^0.5)+(1+2^0.5+3^0.5)...+(1+2^0.5+3^0.5+...+n^0.5)

 1 #include<math.h>
 2 #include<stdio.h>
 3 double fun(int n)
 4 {
 5     double s=1,S=0;
 6     for (int i = 2; i <= n+1; i++)//这里判断条件为n+1.
 7     {
 8         S += s;
 9         s += sqrt(i);//2^0.5=2^(1/2)=根号下2=sqrt(2)
10         printf("%f\n", S);
11         printf("%f\n", s);
12     }
13     return S;
14 }
15 void main()
16 {
17   FILE *wf;
18   int n; 
19   double s;
20   printf("\n\nInput n: ");
21   scanf("%d",&n);
22   s=fun(n);
23   printf("\n\ns=%f\n\n",s);
24 /******************************/
25   wf=fopen("out.dat","w");
26   fprintf(wf,"%f",fun(20));
27   fclose(wf);
28 /*****************************/
29 }

 //使用递归解决:

 1 double f(int n)
 2 {
 3     if (n == 1) return 1;
 4     else return sqrt(n) + f(n - 1);
 5 }
 6 double fun(int n)
 7 {
 8     double S=0;
 9     for (int i = 1; i<=n; i++)
10     {
11         S += f(i);
12     }
13     return S;
14 }

 //也可以使用pow函数。功能:求x的y次方。用法:pow(x,y)。

posted @ 2019-03-17 11:51  小大大小  阅读(1438)  评论(0编辑  收藏  举报