Glenn Jordan Chia Glenn Jordan Chia - 1 year ago 233
C++ Question

Find the lowest of 4 variables using only else-if statements, C++

I just started c++ not too long ago. I want to find the lowest of 4 variables using only if-else statements. So far this is what i could think of. Is there anyway to shorten this?

float lowest;

if (assignment1<assignment2 && assignment1<assignment3 && assignment1<assignment4)
assignment1 == lowest;

else if (assignment2<assignment1 && assignment2<assignment3 && assignment2<assignment4)
assignment2 == lowest;

else if (assignment3<assignment1 && assignment3<assignment2 && assignment3<assignment4)
assignment3 == lowest;

assignment4 == lowest;

Answer Source

Are you allowed to do multiple assignments to lowest? If so:

float lowest = assignment1;

if (assignment2 < lowest)
    lowest = assignment2;

if (assignment3 < lowest)
    lowest = assignment3;

if (assignment4 < lowest)
    lowest = assignment4;

By keeping the smallest value inside lowest, we can simply check each value against lowest, and update lowest when a smaller value is found.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download