c - 为什么我的程序不会停止循环?

标签 c loops for-loop while-loop putty

我的任务是使用两种不同类型的循环(For、While、do While)。任务是要求用户输入1到10之间的数字,然后程序将从0开始计数到用户数。此外,如果用户输入 1 到 10 之外的数字,程序必须能够显示错误消息并要求用户再次输入数字。代码中包含错误消息并提示再次输入数字的部分工作得很好。但是,当我输入范围内的数字时,它要么不执行任何操作,要么从 0 到其数字无限次计数,并且不会停止循环计数。请帮忙!

#include <stdio.h>

int main(void)

{
    //Variables
    int num;
    int zero;

    //Explains to the user what the program will do
    printf("This program will count from 0 to a number you pick.\n\n");

    //Asks the user to input a value
    printf("Please enter a number (between 1 and 10): \n");
    scanf("%d", &num);


    //If the correct range was selected by the user
    while ( num >= 1 && num <= 10 )
    {
            for ( zero = 0; zero <= num; zero++ )
            {
                    printf("%d...", zero);

            }
    }

    //If a value outside of the accepted range is entered
    while ( num < 1 || num > 10)
    {
            printf("I'm sorry, that is incorrect.\n");
            printf("Please enter a number (between 1 and 10): \n");
            scanf("%d", &num);
    }


    printf("\n\n\n");

    return 0;


}

最佳答案

 while ( num >= 1 && num <= 10 )
    {
            for ( zero = 0; zero <= num; zero++ )
            {
                    printf("%d...", zero);

            }
    }

如果 num 介于 1 和 10 之间,则将永远运行,因为 num 在循环内不会更改 - 一旦进入,就永远处于循环中。

如果您输入“坏”值,那么您将跳过此步骤并进入第二个 while 循环。然而,一旦您通过输入“好”值退出 while 循环,剩下要执行的就是

printf("\n\n\n");

return 0;

您需要删除第一个 while 循环并将第二个循环移到 for 循环上方:

#include <stdio.h>

int main(void)

{
    //Variables
    int num;
    int zero;

    //Explains to the user what the program will do
    printf("This program will count from 0 to a number you pick.\n\n");

    //Asks the user to input a value
    printf("Please enter a number (between 1 and 10): \n");
    scanf("%d", &num);

    //If a value outside of the accepted range is entered
    while ( num < 1 || num > 10)
    {
            printf("I'm sorry, that is incorrect.\n");
            printf("Please enter a number (between 1 and 10): \n");
            scanf("%d", &num);
    }

   for ( zero = 0; zero <= num; zero++ )
   {
            printf("%d...", zero);

   }

    printf("\n\n\n");

    return 0;
}

关于c - 为什么我的程序不会停止循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19284865/

相关文章:

PHP foreach 类别和项目

java - 我应该在循环之前还是循环中创建对象 "Random r"

swift - 我想在 Swift 中创建一个乘法表,但出现以下错误

c - 将字符串直接发送到宏与从数组发送的结果不同

c - Valgrind - strcpy 大小为 1 的无效写入

c - 如何使用 C 中的指针对大小未知的数字数组进行排序

bash - 在 bash 中循环遍历行和多列

java - 是否可以在 Java 中声明多个 'for' 循环终止?

javascript - 比较数组中的相邻元素并选择每对中较小的一个

c - 如何在 C 中的共享内存中创建信号量?