我在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