【问题标题】:Comparison operator in for loop (C language)for循环中的比较运算符(C语言)
【发布时间】:2014-05-12 15:42:06
【问题描述】:

我正在尝试用 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;

}

提前致谢!

【问题讨论】:

  • 只有在第二条语句为真时才会进入循环。 0 == n 是假的。
  • 下面有一些很好的答案,但如果你尝试解释为什么你认为你的初始版本会起作用,它可能会帮助你理解一点。

标签: c factorial comparison-operators


【解决方案1】:

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

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

所以它只有在n==1时才会做任何事情,加上循环只能运行0或1次。

【讨论】:

    【解决方案2】:

    for 中的测试甚至在第一个循环之前检查

    for (i = 1; i == 6; i++) {
        // loop will never execute as i is not 6 even before the first loop
    }
    

    【讨论】:

      【解决方案3】:

      有

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

      只要i 和n 相等,您的循环就会循环。如果您为n 输入除1 之外的任何内容,则循环将不会执行。如果你输入1,它只会循环一次,因为下一次迭代i将是2,它不再等于n。

      【讨论】:

        猜你喜欢
        • 2018-11-10
        • 2016-03-25
        • 2021-07-02
        • 2017-06-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-19
        • 2014-05-09
        相关资源
        最近更新 更多