改错题
1. 下列给定程序中,函数proc()的功能是:计算并输出h以内的素数之和。h由主函数传给proc()函数。若h的值为80,则函数的值为791。
请修改程序中的错误,使它能得到正确结果。
注意:不要改动main()函数,不得增行或删行,也不得更改程序的结构。
试题程序:
#include<stdlib.h>
#include<conio.h>
#include<stdio.h>
#include<math.h>
int proc(int h)
{
int sum=0,n=0,j,yes;
while(h>=2)
{
yes=1;
for(j=2; j<=h/2; j++)
//****found****
if h%j==0
{
yes=0;
break;
}
//****found****
if(yes==0)
{
sum+=h:
n++:
}
h--:
}
return sum;
}
void main()
{
system("CLS");
printf("%d\n",proc(80));
}
【正确答案】(1)错误:ifh%j==0
正确:if(h%j==0)
(2)错误:if(yes==0)
正确:if(yes)
【答案解析】 由C语言的语法规则可知,if语句的条件必须用括号括起来,因此,“ifh%j==0”应改为“if(h%j==0)”;变量yes=0,说明整数h为非素数,不计入和当中,因此,“if(yes==0)”应改为“if(yes)”。