### If Statements

Hi I have worked on a question where you input 3 positive number and the program gives you the middle of those so if i put in 1,2,3 it will give me 2. Here is the code but it is not complete. I do not know what I am missing because if I put the numbers : 9,6,7 or 4,2,3 it does not out put the correct number. Also if you think there is a better way of writing this code, please tell me!

 ``12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455`` ``````//Challenge 4#include using namespace std; int main () { int x; int y; int z; int counter=0; int m=0; cout<<"Please input the weight of all three bowls: "; cin>>x; cin>>y; cin>>z; if(x>y&&y>z) m=y; if(x>y&&yz&&y>z) m=y; if(x>z&&yx&&xx&&x>z) m=x; if(y>z&&z>x) m=z; if(y>z&&zy&&y>x) m=y; if(z>y&&yx&&y>x) m=y; if(z>x&&y

try using `else if` statements. This ensures that the tests are exclusive and that you don't identically write to m on two coinsurance.

If I were to do this, I'd probably do it like so:

 ``12345678910111213141516`` ``````#include // std::cin, cout, endl #inlcude // std::sort using namespace std; int main() { int vals[3]; cout<<"Please input the weight of all three bowls: "; for (int i = 0; i < 3; ++i) cin >> vals[i]; sort( vals , vals+3 ); cout << vals[1] << endl; return 0; }``````

Or a little more generic:
 ``123456789101112131415`` ``````#include #include #include // Returns the median of all elements in the range [first, last) template typename std::iterator_traits::value_type Median(Iter first, Iter last) { std::vector::value_type> arr( first, last ); std::sort( arr.begin(), arr.end() ); return arr.at( arr.size()/2 ); }``````
Last edited on
If I make minimum changes to your code, this is what I'll get:
 ``12345678910111213141516171819202122`` ``````//Challenge 4 #include using namespace std; int main () { int x, y, z, m; cout<<"Please input the weight of all three bowls: "; cin>>x; cin>>y; cin>>z; if ( x>=y&&y>=z || x<=y&&y<=z ) m=y; else if ( x>=z&&z>=y || x<=z&&z<=y ) m=z; else m=x; cout<
great stuff! Thank you so much Stewbond!
Topic archived. No new replies allowed.