为什么在输入-1时循环不会中断?

时间:2016-10-16 08:47:46

标签: c loops while-loop

我试图解决我遇到的库问题,当我输入-1时,我不能让while循环停止。我需要按照最近的顺序排列书籍,我想从书号开始。但我无法让它发挥作用。

#include<stdio.h>
#include<conio.h>
int main()
    {
    int i, j, temp, bk_no[20],count=0;
    printf("==========ACCESSING LIBRARY==========\n");

    while(bk_no[count]!=-1)
        {
        printf("What is the books number in the series?\n");
        scanf("%d",&bk_no[count]);
        count++;
        }

    for ( i = 0; i<count; i++ )
        {
        printf("%d",bk_no[i]);
        }

    printf("\n");
    for ( i = 0; i<count; i++ )
        {
        for ( j = 0; j<count-i; j++ )
            {
            if ( bk_no[j]>bk_no[j+1] )
                {
                temp = bk_no[j];
                bk_no[j] = bk_no[j+1];
                bk_no[j+1] = temp;
                }
            }
        }

    for ( i = 0; i<count; i++ )
        {
        printf("%d",bk_no[i]);
        }
    }

3 个答案:

答案 0 :(得分:1)

下次你正在递增计数值     循环检查它在索引中查找的条件前进到已设置的条件      -1

 //this is not the right code i am jush hilighting where you may have gone wrong
 while(bk_no[count]!=-1)
    {
    printf("What is the books number in the series?\n");
    scanf("%d",&bk_no[count]);
    count++;//sence you are incrementing the value of the count the next time the while
//loop checks the condition it looks in a index forward to the one which is set
 // -1
    }

答案 1 :(得分:0)

因为您在循环条件中比较的bk_no[count]和您在bk_no[count]读取的-1不同,因为在循环结束时,您会增加count

您可以使用do-while循环或在读取输入后立即检查:

  while(count < sizeof bk_no/sizeof bk_no[0]) {
        printf("What is the books number in the series?\n");
        scanf("%d", &bk_no[count]);
        if (bk_no[count] == -1) break;
        count++;
  }

请注意,bk_no只能存储20个元素。因此,您无法无限地增加它,而无需检查它是否会溢出。

另请注意,scanf()不是交互式输入的最佳工具。请参阅:http://c-faq.com/stdio/scanfprobs.html

答案 2 :(得分:0)

查看while循环每次迭代结束时会发生什么:您读入bk_no[count],然后增加count,然后控制返回到循环的开头您将book[count]-1 count 的新值进行比较。你不是要比较你从输入中读取的最后一个数字,而是在那里等待的一些单元化内存准备存储下一次读取的结果。

您需要在增量之前进行比较并退出,在此之前您实际上不再需要任何条件:

while(1)
    {
    printf("What is the books number in the series?\n");
    scanf("%d",&bk_no[count]);
    if(bk_no[count]!=-1) break;
    count++;
    }

编辑:使用空出的条件空间检查数组绑定溢出为P.P.写了!

相关问题