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

时间:2021-09-13 07:15:57

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

 #include <stdio.h>

 float fun(int  n)
{
float s=1.0;
int x=;
for (int i = ; i <= n; i++)
{
for (int j = i; j > ; j--)
{
x += j;
}
s += / (float)x;
x = ;//切记x归零。
}
return s;
} void main()
{ int n; float s; printf("\nPlease enter N:"); scanf("%d", &n);
s = fun(n);
printf("the result is: %f\n", s); }

//另一种方法:

 float fun(int  n)
{
float s=0.0;
int x=;
for (int i = ; i <= n; i++)//i初始值为1
{
x += i;
s += / (float)x;
}
return s;
}

//使用递归解决

 float fun(int  n)
{
float m = ;
if (n == ) return 1.0;
for (int i = ; i <= n; i++)
{
m += i;
}
return / m + fun(n - );
}

//在形参s所指字符串中寻找与参数c相同的字符,并在其后插入一个与之相同的字符,找不到相同字符则不做处理。

 #include    <stdio.h>
void fun(char *s, char c)
{ int i, j, n;
/**********found**********/
for(i=; s[i]!='\0'; i++)
if(s[i]==c)
{
/**********found**********/
n=;
while(s[i++n]!='\0') n++;//计算之后字符串的长度
for(j=i+n+; j>i; j--) s[j+]=s[j];//依次赋值给下一个元素,也就是元素后移一位。
/**********found**********/
s[j+]=c;
i=i+;
}
}
void main()
{ char s[]="baacda", c;
printf("\nThe string: %s\n",s);
printf("\nInput a character: "); scanf("%c",&c);
fun(s,c);
printf("\nThe result is: %s\n",s);
}