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 } 

//另外一種方法:spa

 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 }

//使用遞歸解決code

 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 }

//在形參s所指字符串中尋找與參數c相同的字符,並在其後插入一個與之相同的字符,找不到相同字符則不作處理。blog

 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 }
相關文章
相關標籤/搜索