【问题标题】:C easy program not working - "if"C 简单程序不工作 - “如果”
【发布时间】:2015-03-14 12:40:21
【问题描述】:

我尝试编写一个简单的程序来比较 3 个数字并打印其中最大的一个,但它一直打印所有 3 个数字,我不明白为什么。这是我的代码:

#include <stdio.h>

int main()
{
  int x = 10;
  int y = 8;
  int z = 3;

  if((x > y) && (x > z));
  {
    printf("%d",x);
  }

  if((y > x) && (y > z));
  {
    printf("%d",y);
  }
  if((z > x) && (z > y));
  {
    printf("%d",z);
  }
  return 0;

}

感谢您的帮助!

【问题讨论】:

  • 不要将分号放在if 语句的末尾。
  • if 语句的末尾有分号。所以你说if (something) empty_statement,然后你的printf 块被任何if 测试不合格。 IOW,它们每次都会执行,因为没有与之关联的条件测试。

标签: c if-statement


【解决方案1】:

删除每个 if 语句末尾的分号。这导致 if 语句运行空语句 (;),然后运行块语句 { printf(...); }

#include <stdio.h>

int main()
{

  int x = 10;
  int y = 8;
  int z = 3;


  if((x > y) && (x > z))
  {
    printf("%d",x);
  }

  if((y > x) && (y > z))
  {
    printf("%d",y);
  }
  if((z > x) && (z > y))
  {
    printf("%d",z);
  }
  return 0;

}

【讨论】:

  • 哦,我自己应该知道的..但是感谢您的快速回答!
【解决方案2】:

你应该使用else,你应该删除if语句后面的分号,ifs后面的分号表示if的主体是空的,其他的东西是正常的代码块

#include <stdio.h>

int main()
{

  int x = 10;
  int y = 8;
  int z = 3;


  if((x > y) && (x > z))
  {
   printf("%d",x);
  }
  else { // Will not make difference in this particular case as your conditions cannot overlap
  if((y > x) && (y > z))
  {
    printf("%d",y);
  }

  else { // Will not make difference in this particular case as your conditions cannot overlap

  if((z > x) && (z > y))
      {
    printf("%d",z);
      }
  }
}
  return 0;

}

【讨论】:

    【解决方案3】:

    if 条件后面有一个分号:

    if((x > y) && (x > z));
    

    分号代替条件为真时要执行的块或语句。就好像你写过:

    if((x > y) && (x > z))
      {
        ;
      }
      {
        printf("%d",x);
      }
    

    您有望看到这将如何无条件地执行打印语句。

    【讨论】:

      【解决方案4】:

      您的问题的答案完全基于在C中使用分号的知识和if语句的语法。

      更多信息请阅读semicolon,对ifsyntax有一个清晰的了解。

      【讨论】:

        【解决方案5】:

        如果为最大值使用附加变量,逻辑会更简单

        #include <stdio.h>
        
        int main()
        {
            int x,y,z, max;
            scanf ("%d", &x);
            max = x;
            scanf ("%d", &y);
            if (y > max)
                max = y;
            scanf ("%d", &z);
            if (z > max)
                max = z;
        
            printf ("max = %d", max);
        
            return 0;
        }
        

        【讨论】:

        • 您的回答没有解释为什么 OP 的 if 语句被忽略了。
        • 更重要的是,它表明还有其他的思考方式。不可思议!
        • 此处不需要 scanf,但感谢您对 maxiumum 变量的好建议。 :)
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多