我试图在C语言中制作基本的阶乘示例程序,但我不明白为什么下面的程序不能正常运行==比较运算符,尽管它与<=运算符完全正常。
非功能性的版本:
#include <stdio.h>
int main()
{
int i, n, fact=1;
printf("Enter a number:");
scanf("%d", &n);
for(i=1; i==n; i++)
{
fact=fact*i;
}
printf("Factorial of %d is %d", n, fact);
return 0;
}
功能版:
#include <stdio.h>
int main()
{
int i, n, fact=1;
printf("Enter a number:");
scanf("%d", &n);
for(i=1; i<=n; i++)
{
fact=fact*i;
}
printf("Factorial of %d is %d", n, fact);
return 0;
}
已经提前感谢了!
for循环中的条件为while
条件:
int i = 1;
while(i == n)
{
//loopbody
fact=fact*i;
i++;
}
所以只有当n==1
加上循环只能运行0或1次时,它才会做任何事情
for
中的测试甚至在第一个循环之前进行检查
for (i = 1; i == 6; i++) {
// loop will never execute as i is not 6 even before the first loop
}
With
for(i=1; i==n; i++)
只有当i
和n
相等时,循环才会循环。如果在n
中输入1
以外的任何值,则循环将不会执行。如果输入1
,它将只循环一次,因为下一次迭代i
将是2
,不再等于n
。