问答题 下列给定程序中,函数proc()的功能是:求整数x的y次方的低3位值。
例如,整数6的5次方为7776,此值的低3位值为776。
请修改程序中的错误,使它能得出正确的结果。
注意:不要改动main()函数,不得增行或删行,也不得更改程序的结构。
试题程序:
#include<stdio.h>
long proc(int x, int y, long*p)
{
int i;
long t=1;
//****found****
for(i=1; i<y; i++)
t=t*x;
*p=t;
//****found****
t=t/1000;
return 1;
}
void main()
{
long t, r;
int x, y;
printf("/nInput x and y: "); scanf
("%1d%1d", &x, &y);
t=proc(x, y, &r):
printf("/n/nx=%d, y=%d, r=%1d, last=
%1d/n/n", x, y, r, t);
}
【正确答案】
【答案解析】(1)错误:for(i=1; i<y; i++)
正确:for(i=1; i<=y; i++)
(2)错误:t=t/1000;
正确:t=t%1000; [解析] 按照题目中要求求出整数x的y次方的低3位值,整数x的y次方为y个x的乘积,因此,“for(i=1; i<y; i++)”应改为“for(i=1; i<=y; i++)”;要取低3位的值,可以用乘积对1000取模,因此,“t=t/1000;”应改为“t=t%1000;”。