【问题标题】:Infinite do-while loop on C (2 conditions)C上的无限do-while循环(2个条件)
【发布时间】:2018-09-16 02:01:12
【问题描述】:

在我的 C 程序的这一部分中,Do-While 是无限的。我试图做一个
循环用于有人想键入字符串而不是数值的情况。

int main(){
    int cnotas;

    do{
    printf("\nIngrese la Cantidad de Notas del Estudiante\n--------------------------------------------\n");    //asks for the number of grades that are going to be used in the average calculation

    if(cnotas>=1){    //if statement to break the loop when the amount of grades is 1 or more
        break;
    }

    }while(scanf("%d", &cnotas)==0 && cnotas<1);    \\gets the cnotas value and checks if is valid
    promedioe(cnotas);
    system("pause");
}

更新了!

忘了说我想拒绝来自用户的非数字输入,所以程序不会崩溃。

【问题讨论】:

  • 如果你终止输入流,scanf 将永远不会读取任何内容,它会永远循环。如果你输入一个数字,它应该退出
  • 查看if(cnotas&gt;=1)。第一次执行时cnotas的值是多少?
  • 执行永远不会跳出循环,因为非数字字符留在输入缓冲区中,并且总是被 scanf 立即读取。输入无效时需要清空输入缓冲区。

标签: c infinite-loop do-while


【解决方案1】:
  • 在此语句中:while(scanf("%d", &amp;cnotas)==0 &amp;&amp; cnotas&lt;1); 您不希望用户输入任何输入,因为scanf 返回编号。输入成功读取。同时,您期望输入值小于 1。

  • cnotasauto变量所以它的起始值可以是任何值,初始化它。

  • 最好做到:}while(scanf(" %d",&amp;cnotas)==1 &amp;&amp; cnotas&lt;1);

  • 除此之外,您还编写了带有错误标签 \\ 而不是 // 的 cmets。

【讨论】:

  • 如果scanf失败并返回负数怎么办?
  • @KamilCuk 在EOF 的情况下,循环将简单地停止。
  • EOF 在大多数系统上是 -1 并且必须为负数。什么是 scanf 返回任何不同于 1 的值?
  • @KamilCuk 你能解释一下这将如何发生吗?
  • 如果 stdin 在读取一个输入后将被系统关闭。尝试:cnotas; main() { do; while(scanf("%d", &amp;cnotas) == 1 &amp;&amp; cnotas &lt; 1); printf("%d", cnotas); } 并以echo 3 | program 运行(在 linux 上)。这将正确读取大于 1 的 3,然后循环将退出,因为 scanf 将返回 EOF 并且程序将输出 3。
【解决方案2】:

想想你想做什么。您想读取输入,直到读取的值低于 1。

#include <stdlib.h>

int main(){
    int cnotas;
    do {
         printf("\nIngrese la Cantidad de Notas del Estudiante\n--------------------------------------------\n");    //asks for the number of grades that are going to be used in the average calculation

        // Read the input...
        if (scanf("%d", &cnotas) != 1) {
              fprintf(stderr, "scanf error!\n");
              exit(-1);
        }
        // ...until the input is lower then 1    
    } while (cnotas < 1);
    promedioe(cnotas);
    system("pause");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-14
    • 1970-01-01
    • 2018-06-23
    • 1970-01-01
    相关资源
    最近更新 更多