C语言:根据以下公式计算s,s=1+1/(1+2)+1/(1+2+3)+...+1/(1+2+3+...+n) -在形参s所指字符串中寻找与参数c相同的字符,并在其后插入一个与之相同的字符,

//根据一下公式计算s,并将计算结果作为函数返回值,n通过形参传入。s=1+1/(1+2)+1/(1+2+3)+...+1/(1+2+3+...+n)

 1 #include <stdio.h>
 2 
 3 float fun(int  n)
 4 {
 5     float s=1.0;
 6     int x=0;
 7     for (int i = 2; i <= n; i++)
 8     {
 9         for (int j = i; j > 0; j--)
10         {
11             x += j;
12         }
13         s += 1 / (float)x;
14         x = 0;//切记x归零。
15     }
16     return s;
17 }
18 
19 void main()
20 {  int n; float s;22    printf("\nPlease enter N:"); scanf("%d", &n);
23    s = fun(n);
24    printf("the result is: %f\n", s);26 }

//另一种方法:

 1 float fun(int  n)
 2 {
 3     float s=0.0;
 4     int x=0;
 5     for (int i = 1; i <= n; i++)//i初始值为1
 6     {
 7         x += i;
 8         s += 1 / (float)x;
 9     }
10     return s;
11 }

//使用递归解决

 1 float fun(int  n)
 2 {
 3     float m = 0;
 4     if (n == 1) return 1.0;
 5     for (int i = 1; i <= n; i++)
 6     {
 7         m += i;
 8     }
 9     return 1 / m + fun(n - 1);
10 }

//  找不到相同字符则不做处理。

 1 #include    <stdio.h>
 2 void fun(char  *s, char  c)
 3 {  int  i, j, n;
 4 /**********found**********/
 5   for(i=0; s[i]!='\0'; i++)
 6      if(s[i]==c)
 7      {
 8 /**********found**********/
 9         n=0;
10         while(s[i+1+n]!='\0')  n++;//计算之后字符串的长度
11         for(j=i+n+1; j>i; j--)  s[j+1]=s[j];//依次赋值给下一个元素,也就是元素后移一位。
12 /**********found**********/
13         s[j+1]=c;
14         i=i+1;
15      }
16 }
17 void main()
18 {  char  s[80]="baacda", c;
19    printf("\nThe string:  %s\n",s);
20    printf("\nInput a character:  ");  scanf("%c",&c);
21    fun(s,c);
22    printf("\nThe result is:  %s\n",s);
23 }

猜你喜欢

转载自www.cnblogs.com/ming-4/p/10522267.html