[英]C: My loop doesn't seem to work
我是C语言的新手,今天我遇到了一个无法解决的问题,因此我需要一些帮助。 我们得到了以下任务:
“编写一个演示使用“预读”技术的“ while”循环的程序:它要求用户输入(包括)10和100之间的数字,输入零将终止循环。 如果输入的数字小于10或大于100,则会显示一条错误消息(例如,“错误:不允许250”)。 循环终止后,程序将打印输入的数字。
我遇到的问题是,一旦输入有效数字(介于10到100之间),程序就会静止不动,它不会终止也不会循环。 另一方面,如果我输入8、102之类的无效数字,则会循环执行printf(“ Error,不允许%d \\ n”,num);
这是代码:
#include <stdio.h>
main(void)
{
int num;
int counter=1;
printf("Please type in your number between (and including) 10-100\n");
scanf("%d", &num);
if((num <10) || (num >100))
{
printf("Error, %d is not allowed\n", num);
}
while (num > 0)
{
counter++;
if((num <10) || (num >100))
{
printf("Error, %d is not allowed\n", num);
}
counter++;
}
printf("%d numbers were entered!\n", counter);
}
您必须在循环内要求输入数字:
printf("Please type in your number between (and including) 10-100\n");
scanf("%d", &num);
并且请检查scanf
的返回码以检测错误。
最后,您在循环内将计数器增加两次。
问题是您应该在循环内阅读:
while (num != 0)
{
printf("Please type in your number between (and including) 10-100\n");
scanf("%d", &num);
if((num <10) || (num >100))
{
printf("Error, %d is not allowed\n", num);
}
counter++;
}
您也无需将计数器增加2次。
请注意,此代码段还将使counter递增0。如果不需要,则除0以外的数字为counter-1。
您的while循环陷入了无限循环。 您将条件设置为“ WHILE(num> 0)”,但实际上您从未更改过它。 这就是为什么当您的num越界时代码会被捕获的原因。
#include <stdio.h>
void main(void)
{
int num = 0, counter = 0;
printf("Please type in your number between (and including) 10-100\n");
do
{
printf("? ");
scanf("%d", &num);
if (!num)
break;
else if((num < 10) || (num > 100))
printf("Error, %d is not allowed\n", num);
counter++;
} while (num);
printf("%d numbers were entered!\n", counter);
}
这是因为您必须从循环内的输入(scanf)获取数字。 否则,循环将永远循环(如果输入的最合适的数字> 0)。 如果无效,您会看到输出。
已经共享的答案是正确的,您需要在循环中要求输入。 另外,您需要为用户提供退出循环的方法(例如,前哨),如果您知道输入将为非负值,则可以将变量定义为“ unsigned int”,而不是只是“ int”。 参见下面的方法。
#include <stdio.h>
int main(void)
{
unsigned int num = 0, counter = 0;
while (num != -1) // need to control with a sentinel to be able to exit
{
printf("Please type in your number between (and including) 10-100. Enter \"-1\" to exit.\n");
scanf("%d", &num);
counter++; // increase the count by one each successful loop
// set the non-allowed numbers
if((num <10) || (num >100))
{
printf("Error, %d is not allowed\n", num);
counter--; // Need to subtract 1 from the counter if enter a non-allowed number, else it will count them
}
} // end while loop
printf("%d numbers were entered!\n", counter); // Show the use how many correct numbers they entered
} // end main
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.