0
初學者在這裏。我試圖讓用戶輸入一個正數。然而while循環似乎並不適用於用戶輸入時數字不正確的情況。C編程。試圖循環捕捉用戶輸入正數
輸出:
Please enter a positive integer: -3
I'm sorry, you must enter a positive integer greater than zero: why?
I'm sorry, you must enter a positive integer greater than zero: -42
I'm sorry, you must enter a positive integer greater than zero: 42
The positive integer was : 42
Press any key to continue....
代碼:
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
void clear_keyboard_buffer(void);
int main()
{
int k;
printf("Please enter a positive integer: ");
scanf("%d", &k);
if (k > 0)
{
clear_keyboard_buffer();
printf("The positive integer was: %d ", k);
}
while (k<=0)
{
printf("I'm sorry, you must enter a positive integer greater than zero: ");
scanf("%d", &k);
return 0;
}
}
void clear_keyboard_buffer(void)
{
char ch;
scanf("%c", &ch);
while (ch != '\n')
{
scanf("%c", &ch);
}
}
你可以嘗試做一個else語句爲您如果(K > 0),然後把你的時間塊在那裏。 – CurseStacker
@CurseStacker這樣別人 \t { \t \t而(K <= 0) \t \t { \t \t \t的printf( 「對不起,你必須輸入一個正整數大於零」)?; \t \t \t的scanf( 「%d」,&k); \t \t \t返回0; \t \t} \t} – hfu0823
代碼不匹配 「輸出:」 從while循環 – chux