Biggest and smallest of four integers (No arrays, no functions, fewest 'if' statements)

后端 未结 18 2529
北海茫月
北海茫月 2020-12-10 11:29

You see, I\'ve self-taught myself C++ (not completely, I\'m still procrastinating -_-). So, now I started university and they\'re teaching C and they made us do a program of

18条回答
  •  情话喂你
    2020-12-10 11:57

    Here is a solution with no if or elseif or function or macro, but using bit-shift and subtraction instead; only using a single for loop:

    #include 
    int main(){
    
      int num , max, min;
    
      printf("Enter four numbers: ");
      scanf("%d", &num);
      max = min = num;
    
      for(int i = 0; i < 3; i++)
      { 
        scanf("%d", &num);
        max = max * (1 - ( (max-num) >> 31) )
            + num *      ( (max-num) >> 31);
        min = min * (1 - ( (num-min) >> 31) )
            + num *      ( (num-min) >> 31);
      }
    
      printf("\n%d %d", max, min);
      return 0;
    }
    

    The (max-num) >> 31) operation captures the sign of the difference, which when multiplied by the second number yields the minimum value of the comparison.

    This comes from an old SQL coding trick from the days before there was a CASE WHEN construct in that language.

提交回复
热议问题