【问题标题】:Why does the loop not break upon inputting -1?为什么输入-1时循环不会中断?
【发布时间】:2016-10-16 08:47:45
【问题描述】:

我正在尝试解决我遇到的一个库问题,当我输入 -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]);
        }
    }

【问题讨论】:

    标签: c loops while-loop


    【解决方案1】:

    感觉你在下一次 while 时递增计数的值 循环检查它在索引中查找的条件转发到设置的条件 -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
        }
    

    【讨论】:

      【解决方案2】:

      因为您在循环条件中比较的bk_no[count] 和您读取-1bk_no[count] 不同,因为在循环结束时,您增加了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

      【讨论】:

        【解决方案3】:

        看看在你的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.写了!

        【讨论】:

          猜你喜欢
          • 2018-07-20
          • 2021-04-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-11-06
          • 2021-06-17
          相关资源
          最近更新 更多