Given the numbers a, b and c. Find the sum of the largest and smallest of these numbers. The algorithm must be optimal and have the smallest possible number of comparisons. I decided it this way:

#include "stdafx.h" #include <iostream> using namespace std; void main() { double a, b, c; cout << " Enter a = "; cin >> a; cout << " Enter b = "; cin >> b; cout << " Enter c = "; cin >> c; double Suma; if (a < b && a < c) if (b > a&&b > c) Suma = a + b; else if (c > a&&c > b) Suma = a + c; if (b < a&&b < c) if (a > b&&a > c) Suma = b + a; else if (c > a&&c > b) Suma = b + c; if (c < a&&c < b) if (a > b&&a > c) Suma = c + a; else if (b > a&&b > c) Suma = c + b; cout << " Suma : " << Suma << endl; } 

Please write, can you decide better

  • one
    "make for me"? - TEA
  • 2
    if there are three numbers, then the minimum number of comparisons is 3. There is no way less. - KoVadim
  • possible for 2 and a half "on average" - vp_arth
  • No comparison is needed at all. MAXi(a,b) = (a+b+ABS(ab))/2 MAXi(a,b,c)=MAXi(a,MAXi(b,c)) . Similarly for the minimum. And fold. - Akina
  • I need to deal with the conditions - Boris Makhlin

2 answers 2

But with two comparisons it turns out, if you do not need to know which of them is the minimum and which is the maximum. The main thing to find the middle of them:

 int x,y, z; cin >> x >> y >> z; int d1 = x - y, d2 = x - z, d3 = y - x, d4 = y - z; if (d1*d2 < 0) cout << y + z; else if (d3*d4 < 0) cout << x + z; else cout << y + x; 
  • @goldstar_labs, I forgot about this task, but you are reminded, now appreciate - AR Hovsepyan
  • Yes, there is a place to be, thanks for the decision) - goldstar_labs
 int sum = max(x, max(y, z)) + min(x, min(y, z)); 
  • 3 comparisons - AR Hovsepyan
  • @ARHovsepyan 4 - goldstar_labs
  • @goldstar_labs, yes, even 4 - AR Hovsepyan