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

后端 未结 18 2499
北海茫月
北海茫月 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条回答
  •  -上瘾入骨i
    2020-12-10 12:11

    As per the OP's condition

    But seeing that all we've covered in class for now are loops and decision statements. Is there a more elegant way of doing this? One which uses fewer ifs?

    Only one if and one else if statement and one for loop can do this task. Simple and short!

    #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);
            if (max < num)
                max = num;
            else if (min > num)
                min = num;
        }
    
        printf ("The smallest and largest of given four numbers are %d and %d respectively.\n", min,  max);
        return 0;
    }
    

提交回复
热议问题