我在C中編寫了以下代碼以製作計算任意數字階乘的程序。使用isdigit驗證輸入用於階乘程序
我想添加一些驗證/錯誤處理,例如防止輸入隨機字符,浮點數或負值,所以我使用了isdigit
函數。
不幸的是,有一個隱藏的問題,我不知道如何解決。當我輸入任何輸入時,即使它是正數,它也認爲它是錯誤的(即不是數字)。
#include <stdio.h>
#include <ctype.h>
int main()
{
char choice;
unsigned long long int factorial=1;
int counter,number;
for(;;)
{
printf("Please , enter a positive integer number only : ");
scanf("%d",&number);
fflush(stdin);
if(isdigit(number))
{
for(counter=number;counter>1;counter--)
factorial*=counter;
printf("The factorial of number %d is %llu",number,factorial);
}
else
{
printf("\a\aError\n");
continue;
}
printf("\n1-Press c or C if you want to calculate the factorial of a new number\n2-Press any key if you want to exit the program\n ");
scanf("%c",&choice);
if(choice=='c'||choice=='C')
{
factorial=1;
system("cls");
continue;
}
else
return 0;
}
}
請注意12!是符合32位(無符號)整數的最大值,並且是20!是符合64位(無符號)整數的最大值。 – 2014-09-28 03:03:02
除了答案,建議刪除'fflush(stdin)'並將'scanf(「%c」,&choice);'改爲'scanf(「%c」,&choice);'(增加空格)。這將消耗可選的前導空白,包括前面的行。 –
chux
2014-09-28 03:28:59