2015年计算机二级C语言上机操作题及答案(95)
发布时间:2011/7/28 15:44:51 来源:城市学习网 编辑:ziteng
第一题:给定程序功能是计算S=f(-n)+f(-n+1)=…+f(0)+f(1)+f(2)+…+f(n)的值。
例如,当n为5时,函数值应为:10.407143.
f(x)= 请勿改动主函数main和其他函数任何内容,仅在横线上填入所编写的若干表达式或语句。
#include
#include
double f(double x)
{
if (fabs(x-0.0)<1e-6 || fabs(x-2.0)<1e-6)
return ___1___;
else if (x < 0.0)
return (x-1)/(x-2);
else
return (x+1)/(x-2);
}
double fun(int n)
{
int i;
double s = 0.0, y;
for (i=-n; i<=___2___; i++)
{
y = f(1.0*i);
s += y;
}
return ___3___;
}
main()
{
printf("%lf\n", fun(5));
}
答案:
第一处 0.0或0或 (double)0
第二处 n
第三处 s [NextPage] 第二题:
下列给定程序中,函数fun的功能是:计算并输出下列数的前N项之和Sn,直到Sn+1大于q为止,q的值通过形参传入。
例如,若q的值为50.0,则函数值为49.394948.
请改正程序中的错误,使它能得出正确的结果。
注意,不要改动main函数,不得增行或删行,也不得更改程序的结构!
#include
#include
double fun(double q)
{
int n;
double s, t;
n = 2;
s = 2.0;
while (s <= q)
{
t = s;
/********found********/
s = s + (n+1)/n;
n++;
}
printf("n=%d\n", n);
/********found********/
return s;
}
main()
{
printf("%f\n", fun(50));
}
答案:
第一处 s=s+(n+1)/n;应改为s=s+(double)(n+1)/n;
第二处 return s; 应改为 return t; [NextPage] 第三题:假定输入的字符串中只包含字母和*号。请编写函数fun,它的功能是:使字符串的前导*号不得多于n个;若多于n个,则删除多余的*号;若少于或等于n个,则什么也不做,字符串中间和尾部的*号不删除。
例如,若字符串中的内容为*******A*BC*DEF*G****,假设n 的值为4,删除后,字符串中的内容则应当是 ****A*BC*DEF*G****;若n 的值为8,则字符串中的内容仍为*******A*BC*DEF*G****。N的值在主函数中输入。在编写函数时,不得使用C语言提供的字符串函数。
请改正程序中的错误,使它能得出正确的结果。
注意,不要改动main函数,不得增行或删行,也不得更改程序的结构!
#include
#include
void fun( char *a, int n )
{
}
main()
{
char s[81];
int n;
FILE *out;
printf("Enter a string:\n");
gets (s);
printf("Enter n: ");
scanf ("%d",&n);
fun( s,n );
printf("The string after deleted:\n");
puts(s);
out=fopen("out.dat","w");
strcpy(s, "*******A*BC*DEF*G****");
fun(s, 4);
fprintf(out, "%s", s);
fclose(out);
}
答案:
void fun( char *a, int n )
{
int i=0, k=0;
char *t=a;
while(*t==’*’)
{
k++;
t++;
}
t=a;
if(k>n)
t=a+k-n;
while(*t)
{
a[i]=*t;
i++;
t++;
}
a[i]=’\0’;
}