C easy program not working - “if”

后端 未结 5 1245
情书的邮戳
情书的邮戳 2020-12-22 00:30

I tried to write an easy program that compares 3 numbers and prints the biggest of them but it keeps printing all 3 of them and I don\'t get why. That\'s my code:

         


        
相关标签:
5条回答
  • 2020-12-22 00:53

    You have a semicolon after your if condition:

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

    The semicolon takes the place of the block or statement to be executed when the condition is true. It's as if you had written:

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

    You can hopefully see how this will execute the print statement unconditionally.

    0 讨论(0)
  • 2020-12-22 00:54

    Remove the semicolon at the end of each if statement. That is causing the if statement to run the null statement (;) and then subsequently run a block statement { 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;
    
    }
    
    0 讨论(0)
  • 2020-12-22 01:03

    The logic is simplier if you use an additional variable for maximum

    #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;
    }
    
    0 讨论(0)
  • 2020-12-22 01:09

    The answer to your question is purely based on the knowledge of using semicolon in C and syntax of if statement.

    For more information read semicolon and have a clear understanding ofifsyntax.

    0 讨论(0)
  • 2020-12-22 01:15

    You should use else , you should remove the semi-colons after the if statements , the semi colons after ifs means that the body of the if is empty and the other stuff is a normal block of code

    #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;
    
    }
    
    0 讨论(0)
提交回复
热议问题