我的任务是使用两种不同类型的循环(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/