強制用戶輸入一個正整數,並把用戶放到一個循環中直到他們這樣做。如何強制用戶輸入正整數?
所以我想要的一切,包括字符不允許剛過> 0
我試過如下:
while (i < 0) do {
printf("please input a number that's positive");
scanf("%d", i);
}
強制用戶輸入一個正整數,並把用戶放到一個循環中直到他們這樣做。如何強制用戶輸入正整數?
所以我想要的一切,包括字符不允許剛過> 0
我試過如下:
while (i < 0) do {
printf("please input a number that's positive");
scanf("%d", i);
}
對於正整數使用下面的代碼
int i;
do
{
printf("please input a number that's positive");
scanf("%d", &i);
}while (i < 0);
C語言提供沒有錯誤檢查用戶輸入。預計用戶輸入正確的數據類型。例如,如果用戶在預期有整數值時輸入字符,程序可能會進入無限循環或異常中止。
我會這樣做:聲明char term
和int wrong = 0
。上述
do {
printf("Enter a number: ");
fflush(stdin);
if (scanf("%d%c", &n, &term) != 2 || term != '\n' || n <= 0) {
printf("Only positive numbers.\n");
wrong = 1;
}
else {
wrong = 0;
//do something here if correct;
}
} while (wrong);
代碼檢測無效的輸入如果用戶輸入的字符和數字,或負數(和零)的混合物。
但是,它不檢測用戶是否在前面輸入尾隨零,然後輸入有效數字,例如。 001
或00000738
。如果其他人可以弄清楚,請在下面分享。謝謝! :)
'fflush(stdin)'會導致未定義的行爲。希望你的意思是'fflush(標準輸出)',以便用戶看到提示。 – 2014-03-06 21:47:26
這是一個函數的另一種替代方法,它需要一個char str[20]
(可能是20個元素),分析字符串以檢查正整數,並相應地返回0
或1
。最後,使用atoi()
將該字符串轉換爲整數。
int checkPositiveIntegers(char str[]) {
char *ptr = str;
if (*ptr == '-' || *ptr == '0') //checks for negative numbers or zero
return 1;
else {
do {
if (isdigit(*ptr) == 0) { //checks for non-digit at ptr location; isdigit() returns 0 if non-digit
return 1;
break;
}
ptr++;
} while (*ptr != '\0' && *ptr != '\n');
return 0; //returns 0 if positive integer
}
}
因此函數只接受從1到9,999,999,999,999,999,999正數(高達19位數字是否char str[]
持有20個元件)。
但是,如果將字符串轉換回int n = atoi(str);
,則可以達到的最大值將是2,147,483,647,因爲n
被聲明爲有符號整數。利用不同的數據類型進行探索。
希望這會有所幫助! :)
有庫函數可以將字符串轉換爲整數;沒有必要在這裏重新發明輪子。 – 2014-03-06 21:48:24
是的,我知道Matt McNabb,我想知道是否有人想知道這個函數是如何寫成的。 – 2014-03-06 21:56:22
這兩個while函數管理數字,int k是隻能設置在20以下的設置整數,第一個while循環生成一個語句,如果該數字大於20,則會調用另一個掃描 第二個循環打印ak * k框。 希望這有助於。
int main ()
{
int i, j,k;
printf("Please enter Box size:\n\n");
scanf("%d",&k);
while(k>20){
printf("Please enter a value below 20\n\n");
scanf("%d"),&k;
}
while(k<=20)
{
for (i = 0; i < k; i++)
{
printf("\n");
for (j = 0; j < k; j++)
{
printf("#");
}
}
return 0;
}
}
while(i <0)do {printf(「請輸入一個正數」); scanf(「%d」,i); } – 2012-07-27 16:57:33
'while'循環適用於此。根據您需要與&&或||進行分組的條件,接受用戶輸入後放置它。 – ChiefTwoPencils 2012-07-27 16:57:59
如何禁用所有輸入的字符? – 2012-07-27 16:59:06