[英]Why won't my while loop initiate in this c code?
我是C語言編程的新手,但是我不明白為什么編譯后此代碼無法正常運行。 現在,我只希望它取10到100之間的數字而不會出錯。 然后,我將為錯誤添加return 1,為成功添加0。
#include <stdio.h>
#include <stdlib.h>
int intGet(int, int);
int error();
int main(void)
{
int Min, Max, UserIn;
Min = 10;
Max = 100;
printf("Enter a number in between [10 -100]: \n");
scanf("%d", &UserIn);
printf("Read %d\n", UserIn);
while (UserIn < Min && UserIn > Max)
{
printf("Invalid \n");
scanf("%d", &UserIn);
}
/* What I did to fix
while ((UserIn > Min) || (UserIn < Max)){
printf("Enter a number in between [10 -100]: \n");
scanf("%d",&UserIn);
printf("Read %d\n",UserIn);
while ((UserIn < Min) || (UserIn > Max)){
printf("Invalid \n");
scanf("%d", &UserIn);
printf("Read %d\n", UserIn);
}
}*/
return EXIT_SUCCESS;
}
int intGet(int min, int max)
{
}
int error()
{
}
while (UserIn < Min && UserIn > Max)
userIn
不能同時滿足這兩個條件。 更改為:
whihe (userIn < Min || userIn > Max)
您確實意識到scanf
確實會返回值嗎? 參見http://linux.die.net/man/3/scanf
如果它不返回1,那么您需要“吃掉”一些輸入。
最好閱讀一個字符串並進行解析。
也
while (UserIn < Min && UserIn > Max)
應該
while (UserIn < Min || UserIn > Max)
更換
while (UserIn<Min && UserIn>Max){
與:
while (UserIn<Min || UserIn>Max){
你也可以用do ... while代替while循環。 那么您將不會再進行兩次scanf
為了幫助您調試此代碼,請嘗試以下代碼:
while ((UserIn < Min) || (UserIn > Max))
{
printf("Invalid \n");
scanf("%d", &UserIn);
printf("Read %d\n", UserIn);
}
此外,僅當Userin的第一個輸入值小於10或大於100時,才會運行while循環。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.