用循环求阶乘
正确程序:
#include<stdio.h>
int main(void)
{
long a = 0L;
long fac = 0L;
long b = 0L;
printf("Enter an integer number(q to quit): ");
while (scanf("%ld", &a) == 1 && a >= 0)
{
if (a == 0)
{
printf("Factorial of 0 is 1.\n");
printf("Enter an integer number(q to quit): ");
}
else
{
for (fac = 1, b = a; b >= 1; b--)
{
fac *= b;
}
printf("Factorial of %ld is %ld.\n", a, fac);
printf("Enter an integer number(q to quit): ");
}
}
printf("Bye.\n");
return 0;
}
结果:
Enter an integer number(q to quit): 1
Factorial of 1 is 1.
Enter an integer number(q to quit): 2
Factorial of 2 is 2.
Enter an integer number(q to quit): 3
Factorial of 3 is 6.
Enter an integer number(q to quit): 4
Factorial of 4 is 24.
Enter an integer number(q to quit): 5
Factorial of 5 is 120.
Enter an integer number(q to quit): 0
Factorial of 0 is 1.
Enter an integer number(q to quit): q
Bye.
一个错误程序及原因分析:
#include<stdio.h>
int main(void)
{
long a = 0L;
long fac = 1L;
printf("Enter an integer number(q to quit): ");
while (scanf("%ld", &a) == 1 && a >= 0)
{
if (a == 0)
{
printf("Factorial of 0 is 1.\n");
printf("Enter an integer number(q to quit): ");
}
else
{
for (long b = a, fac = 1; b >= 1; b--)
{
fac *= b;
}
printf("Factorial of %ld is %ld.\n", a, fac);
printf("Enter an integer number(q to quit): ");
}
}
printf("Bye.\n");
return 0;
}
结果:
Enter an integer number(q to quit): 1
Factorial of 1 is 1.
Enter an integer number(q to quit): 2
Factorial of 2 is 1.
Enter an integer number(q to quit): 3
Factorial of 3 is 1.
Enter an integer number(q to quit): 4
Factorial of 4 is 1.
Enter an integer number(q to quit): q
Bye.
此处求阶乘的结果全是 1.
原因分析: