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

后端 未结 18 2541
北海茫月
北海茫月 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 12:05

    One idea may be to compute the maximum and minimum of the first two numbers. Then, you compare the rest of the numbers in pairs. The greater one of each pair is compared against the current maximum, and the smaller one of each pair is compared against the current minimum. This way you do 3 comparisons for every 2 elements, which is slightly more efficient than Arpit's answer (2 comparisons for each element).

    In code:

    #include 
    
    int main(int argc, char **argv) {
        int a, b, c, d;
        printf("Enter four integers (separated by space): ");
        scanf("%d %d %d %d", &a, &b, &c, &d);
    
        int max, min;
        if (a > b) {
           max = a;
           min = b;
        }
        else {
           max = b;
           min = a;
        }
    
        if (c > d) {
           if (c > max) {
              max = c;
           }
           if (d < min) {
              min = d;
           }
        }
        else {
           if (d > max) {
              max = d;
           }
           if (c < min) {
              min = c;
           }
        }
        printf("max = %d, min = %d\n", max, min);
        return 0;
    }
    

提交回复
热议问题