c语言的程序编译正确,而运行出现了问题,怎么回事

来源:百度知道 编辑:UC知道 时间:2024/05/26 17:59:32
完整的程序
#include <stdio.h>
int fun(int x)
{ int n, s1, s2, s3, t;
/**********found**********/
n=0;
t=100;
/**********found**********/
while(t<=x)
{ s1=t%10; s2=(t/10)%10; s3=t/100;
if(s1+s2+s3==15)
{ printf("%d ",t);
n++;
}
/**********found**********/
t++;
}
return n;
}
main()
{ int x=-1;
while(x>999||x<0)
{ printf("Please input(0<x<=999): "); scanf("%d",&x); }
printf("\nThe result is: %d\n",fun(x));
}

还有其中主函数里有个int x=-1;为什么是x=-1而不是x=1?

关键在于主函数中的while循环,x>999||x<0当它为true时才会运行while循环,所以x应该为999以上或0一下的数才会执行while循环,如果x赋值为1的话while循环将不执行,而且你输入的必须是0--999之间的数,否则不会跳出循环,程序没问题,你再看看

x = -1才满足循环条件,没问题了

#include <stdio.h>
int fun(int x)
{
int n, s1, s2, s3, t;
/**********found**********/
n=0;
t=100;
/**********found**********/
while(t<=x)
{
s1=t%10; s2=(t/10)%10; s3=t/100;
if(s1+s2+s3==15)
{
printf("%d ",t);
n++;
}
/**********found**********/
t++;
}
return n;
}
void main()
{
int x=-1;
while(x>999||x<0)
{
printf("Please input(0<=x<=999): ");
scanf("%d",&x);
fflush(stdin);
}
printf("\nThe result is: %d\n",fun(x));
}

main 函数前面应加void。
除此之外程序没有什么问题。
初始化x为-1是为了进入while循环,而while循环又是为了保证输入的数据在0<x<=999之间。试想,当