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!
//Challenge 4#include <iostream>
usingnamespace 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&&y<z)
m=z;
if(x>z&&y>z)
m=y;
if(x>z&&y<z)
m=z;
if(y>x&&x<z)
m=z;
if(y>x&&x>z)
m=x;
if(y>z&&z>x)
m=z;
if(y>z&&z<x)
m=x;
if(z>y&&y>x)
m=y;
if(z>y&&y<x)
m=x;
if(z>x&&y>x)
m=y;
if(z>x&&y<x)
m=x;
//does not work for 967 or 423 ....?? why?
cout<<m<<endl;
return 0;
}
try using elseif 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream> // std::cin, cout, endl
#inlcude <algorithm> // std::sort
usingnamespace 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <vector>
#include <iterator>
#include <algorithm>
// Returns the median of all elements in the range [first, last)
template <class Iter>
typename std::iterator_traits<Iter>::value_type
Median(Iter first, Iter last)
{
std::vector<typename std::iterator_traits<Iter>::value_type> arr( first, last );
std::sort( arr.begin(), arr.end() );
return arr.at( arr.size()/2 );
}
//Challenge 4
#include <iostream>
usingnamespace 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;
elseif ( x>=z&&z>=y || x<=z&&z<=y )
m=z;
else
m=x;
cout<<m<<endl;
return 0;
}