一个很简单的C语言问题,我就是想实现:输入一系列数字,然后以0为标志结束输入,再输出之前输入的数字

#include <stdio.h>
#include <conio.h>
int main()
{
int a[10];
int i=0;int n=0;
while(a[i]!=0)
{
scanf("%d",&a[i]);
fflush(stdin);
i++;
}
n=i;
printf("\n");
for(i=0;i<n;i++)
{
printf("%d ",a[i]);
}
getch();
}
我不知道哪里错了,请大家帮帮忙

a[10] 没有初始化,里面装的是上一次使用的数据,不知道具体是多少呢- -|||
建议你先全部初始化为,再用do while 或者先输入a[0] 再循环。
而且,最近老是看见人用 fflush(stdin); 有必要吗。。。
问一下,你的输入数据是怎么输入的,如果是 先将所有数据都输入再按回车的话就有问题了。
因为你所有数据都在缓冲区里,你读完一个数据之后就清空缓冲区了,结果后面的数据都被清空了。如果是每输入一个数据,按回车就没事。不过那一句仍然很多余,顺便说一下,fflush(stdin); 貌似只能用于VC(微软自己扩展的)
而且嘛,你是先 i++ 在判断 a[i] 是否等于零的,一直在判断你为输入的数据是否等于0,应该改为 a[i-1]; 在循环体之前输入a[0] 或者用do while 算了
或者直接就给一个死循环,然后再循环体里面判断a[i] 是否等于 0 等于就break
还有 ,n=0.。。。杯具了吧,循环结束后 i >=0 所以基本上不会有输出。。。应该是
n=i
温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-02-11
#include <stdio.h>
#include <conio.h>
int main()
{
int a[10];
int i=0;int n=0;
do
{
scanf("%d",&a[i]);
i++;
} while (a[i-1]!=0);
n=i;
printf("\n");
for(i=0;i<n;i++)
{
printf("%d ",a[i]);
}
getch();
}

具体哪里错了 自己看看就知道了
第2个回答  2011-02-11
如果你仔细看下a[i]每次的值就会发现它跟你想的不同。我重新写了个
#include <stdio.h>
#include <conio.h>

int main ()
{
int curnum =0; //这次输入的数字
int allnum [10]; //保存输入的数字
int numoff =0; // 保存的数字的个数
while (true) {
printf ("Input a number, type 0 to stop and out put all numbers \n");
scanf ("%d",&curnum);
if (curnum == 0) {
printf ("you typed 0, it's over \n");
break;
}
if (numoff > 9){
printf ("you typed more then 10 numbers, it's over \n");
break;
}
allnum[numoff++] = curnum;
}
printf ("now we will out put all numbers you typed \n");
for (int i = 0; i < numoff; i++)
printf ("%d \n",allnum[i]);
return 0;
}
第3个回答  2011-02-11
错在没有退出循环的条件,当i>=10时,编辑器并不认为a[i]=0;并且我用的编辑器也没有报错,(虽然声明的数组是a【10】,数组越界),建议将循环条件改为while(i<10)
相似回答