for循环中的比较运算符(C语言)

时间:2014-05-12 15:42:06

标签: c factorial comparison-operators

我正在尝试在C语言中制作基本的因子示例程序,但我无法理解为什么以下程序无法正常使用==比较运算符,尽管它与< =运算符完全一致。 / p>

非功能版:

#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;

}

提前谢谢!

3 个答案:

答案 0 :(得分:3)

for循环中的条件是while条件:

int i = 1;
while(i == n)
{
   //loopbody
   fact=fact*i;
   i++;
}

所以它只会在n==1时执行任何操作,加上循环只能运行0或1次。

答案 1 :(得分:2)

即使在第一个循环

之前,也会检查for中的测试
for (i = 1; i == 6; i++) {
    // loop will never execute as i is not 6 even before the first loop
}

答案 2 :(得分:2)

使用

for(i=1; i==n; i++)

只要in相等,您的循环就会循环播放。如果为1输入n以外的任何内容,则循环将不会执行。如果您输入1,则只会循环一次,因为下一次迭代i2不再等于n