编程题:
100.请编写函数fun,其功能是:计算并输出
S=1+(1+20.5)+(1+20.5+30.5)+…+(1+20.5+30.5+…+n0.5)
例如,若主函数从键盘给n输入20后,则输出为s=534.188884。
注意:n的值要求大于1但不大于100。部分源程序给出如下。
请勿改动主函数main和其他函数中的任何内容,仅在函数fun的花括号中填入所编写的若干语句。
#include <math.h>
#include <stdio.h>
double fun(int n)
{
}
main()
{
int n;
double s;
printf(“nnInput n: “);
scanf(“%d”,&n);
s=fun(n);
printf(“nns=%fnn”,s);
}
10.编写函数fun,它的功能是:利用以下所示的简单迭代方法求方程COS(X)-X=0的一个实根。
Xn+1=COS(Xn)
迭代步骤如下:
(1)取x1初值为0.0;
(2)x0=x1,把x1的值赋给x0;
(3)x1=COS(x0),求出一个新的x1;
(4)若x0—x1的绝对值小于0.000001,则执行步骤(5),否则执行步骤(2);
(5)所求x1就是方程COS(X)-X=0的一个实根,作为函数值返回。
程序将输出结果Root=0.739085。
注意:部分源程序给出如下。
请勿改动主函数main和其他函数中的任何内容,仅在函数fun的花括号中填入所编写的若干语句。
#include <conio.h>
#include <math.h>
#include <stdio.h>
float fun()
{
}
main()
{
clrscr();
printf(“Root=%fn”,fun());
}
改错题:
10.下列给定程序中,函数fun的功能是:将s所指字符串中出现的t1所指子串全部替换成t2所指子字符串,所形成的新串放在w所指的数组中。在此处,要求t1和t2所指字符串的长度相同。例如,当s指字符串中的内容为abcdabfab,t1指子串中的内容为ab,t2所指子串中的内容为99时,结果,在w所指的数组中的内容应为99cd99f99。
请改正程序中的错误,使它能得出正确的结果。
注意:不要改动main函数,不得增行或删行,也不得更改程序的结构!
试题程序:
#include <conio.h>
#include <stdio.h>
#include <string.h>
/********found********/
int fun(char *s,char *t1,char *t2,char *w)
{
int i;
char *p,*r,*a;
strcpy(w,s);
while(*w)
{
p=w; r=t1;
/********found********/
while(r)
if(*r==*p)
{
r++;p++;
}
else
break;
if(*r==’’)
{
a=w;
r=t2;
while(*r)
{
*a=*r;
a++;
r++;}
w+=strlen(t2);
}
else
w++;
}
}
main()
{
char s[100],t1[100],t2[100],w[100];
clrscr();
printf(“nPlease enter string s:”);
scanf(“%s”,s);
printf(“nPlease enter substring t1:”);
scanf(“%s”,t1);
printf(“nPlease enter substring t2:”);
scanf(“%s”,t2);
if(strlen(t1)==strlen(t2)){
fun(s,t1,t2,w);
printf(“nThe result is :%sn”,w);
}
else
printf(“Error :strlen(t1)!=strlen(t2)n”);
}
45.下面给定程序中,函数fun的功能是:将s所指字符串中最后一次出现的t1所指子串替换成t2所指子串。所形成的新串放往w所指的数据中。在此处,要求t1和t2所指字符串的长度相同。例如,当s所指字符串中的内容为abcdabfabc,t1所指子串中的内容为ab,t2所指子串中的内容为99时,结果,在w所指的数组中的内容为abcdabf99c。
请改正函数fun中的错误,使它能得出正确的结果。
注意:不要改动main函敛,不得增行或删行;也不得更改程序的结构!
试题程序:
#include <conio.h>
#include <stdio.h>
#include <string.h>
/********found********/
int fun(char *s, char *t1, char *t2, char *w)
{
int i;
char *p, *r, *a;
strcpy( w, s );
/********found********/
while ( w )
{
p = w;
r = t1;
while ( *r )
if ( *r == *p )
{
r++;
p++;
}
else
break;
if ( *r == ‘’ )
a=w;
w++;
}
r = t2;
while ( *r )
{
*a = *r;
a++;
r++;
}
}
main()
{
char s[100], t1[100], t2[100], w[100];
clrscr();
printf(“nPlease enter string S:”);
scanf(“%s”, s);
printf(“nPlease enter substring t1:”);
scanf(“%s”, t1);
printf(“nPlease enter substring t2:”);
scanf(“%s”, t2);
if ( strlen(t1)==strlen(t2) )
{
fun( s, t1, t2, w);
printf(“nThe result is : %sn”, w);
}
else
printf(“nError : strlen(t1) != strlen(t2)n”);
}