改错题
1. 下列给定程序中,函数proc()的功能是:传入一个整数n,计算如下公式的值。
t=1/2-1/3-…-1/n
例如,若输入3,则应输出0.166667。
请修改程序中的错误,使它能得出正确的结果。
注意:不要改动main()函数,不得增行或删行,也不得更改程序的结构。
试题程序:
#include<stdlib.h>
#include<conio.h>
#include<stdio.h>
double proc(int n)
{
double t=1.0;
int i;
for(i=2; i<=n; i++)
//****found****
t=1.0-1/i;
//****found****
}
void main()
{ int m;
system("CLS");
printf("\nPlease enter 1 integer numbers:\n");
scanf("%d",&m);
printf("\n\nThe result is%If\n",proc(m));
}
【正确答案】(1)错误:t=1.0-1/i;
正确:t-=1.0/i;
(2)错误:;
正确:return t;
【答案解析】 从题目中的公式可知,整数n每增加1,其结果为上一次的结果减1/i,因此,“t=1.0-1/i;”应改为“t-=1.0/i;”;由函数的定义可知,函数proc()要把最后所得到的结果返回给主函数,因此,要在函数proc()的最后加上“return t;”。