C 简单程序无法运行 - "if"

C easy program not working - "if"

我试图编写一个简单的程序来比较 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;

}

感谢您的帮助!

你应该使用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;

}

删除每个 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;

}

您的 if 条件后有一个分号:

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

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

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

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

如果你为最大值使用一个额外的变量,逻辑会更简单

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

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

有关详细信息,请阅读 semicolon and have a clear understanding ofifsyntax