0

Least to Greatest

//C++ Program LeastToGreatest //Gabriel Reyes January 16, 2022 CIS-5 #include <iostream> using namespace std; int main() { float n1, n2, n3; cout << "Enter three numbers: "; cin >> n1 >> n2 >> n3; if (n1 >= n2 && n1 >= n3) cout << "Largest number: " << n1; if (n2 <= n1 && n2 >= n3) cout << "Middle number: " << n2; if (n3 <= n1 && n3 <= n2) cout << "Smallest number: " << n3; return 0; } Hello I am trying to make these lines of code print out numbers least to greatest however when i enter it, only the smallest number will pop up, can anyone help me figure out what to do for it to show the least, the middle, and the greatest number? thank you in advanced

17th Jan 2022, 9:33 PM
Gabriel Reyes
3 Answers
+ 2
#include <iostream> #include <vector> #include <bits/stdc++.h> using namespace std; int main() { string lvl[3] = {"Largest number", "Middle number", "Smallest number"}; vector<int> v; int i, n; for(i=0; i<3; i++) { cin >> n; v.push_back(n); } sort(v.begin(), v.end(), greater<int>()); i=0; for (auto x : v) { cout << lvl[i] << "\t: " << x << endl; i++; } return 0; } // Good Luck https://code.sololearn.com/cSOiJS76npph
17th Jan 2022, 10:08 PM
SoloProg
SoloProg - avatar
+ 1
Your code will only work properly if we input numbers from greatest to smallest like 5 4 2 for example. In other cases it will have obscure behavior. You must order the numbers before the if statements using other block of if statements or rewrite the code.
18th Jan 2022, 3:51 AM
Christina Ricci
Christina Ricci - avatar
0
#include <iostream> #include <algorithm> using namespace std; int main() { float n1, n2, n3; cin >> n1 >> n2 >> n3; float min_float = min(min(n1, n2), n3); float max_float = max(max(n1, n2), n3); float total_float = n1 + n2 + n3; cout << "The largest number is " << max_float << endl; cout << "The smallest number is " << min_float << endl; cout << "The middle number is " << total_float - max_float - min_float; return 0; }
17th Jan 2022, 10:21 PM
rodwynnejones
rodwynnejones - avatar