C简易程序不工作 - “如果”

时间:2015-01-15 23:36:15

标签: c if-statement

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

}

感谢您的帮助!

5 个答案:

答案 0 :(得分:3)

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

}

答案 1 :(得分:3)

删除每个if语句末尾的分号。这导致if语句运行null语句(;),然后运行一个块语句{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 :(得分:3)

您的if条件后面有分号:

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

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

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

您可以无条件地看到它将如何无条件地执行print语句。

答案 3 :(得分:1)

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

有关详细信息,请参阅semicolon,并清楚了解if syntax

答案 4 :(得分:0)

如果您使用其他变量获得最大值

,则逻辑会更简单
#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;
}