Inconsistent 'if' statements

I don't understand this one at all. The program below is designed to take three integer inputs and determine which one is the middle (ie is neither the largest nor the smallest value).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
using namespace std;

int main ()
{
    int num1, num2, num3;
    
    cout << "Please enter three whole numbers (integers) separated by spaces:" << endl;
    cin >> num1 >> num2 >> num3;
    
    int mid;

    if (((num2 > num1) && (num3 < num1)) || ((num3 > num1) && (num2 < num1))) mid = num1;
    if (((num1 > num2) && (num3 < num2)) || ((num3 > num1) && (num1 < num2))) mid = num2;
    if (((num1 > num3) && (num2 < num3)) || ((num2 > num3) && (num1 < num3))) mid = num3;
    
    cout << "The middle number is " << mid << endl;
    cin.get();
    cin.get();
}


It works fine, as long as the three integers are all different. It can't handle multiple same values however. But if I add the following statements (or anything similar) at any point in the program, the program always chooses the same input (num1, num2 or num3), regardless of the input value.

1
2
    if ((num1 = num2) || (num1 = num3)) mid = num1;
    if (num2 = num3) mid = num1;


It seems perfectly sensible to me, what am I missing?
Last edited on
This is becouse you used < and >. They dont give a true if the numbers are the same.
You should try using <= and >= instead.

And this:
1
2
if ((num1 = num2) || (num1 = num3)) mid = num1;
if (num2 = num3) mid = num1;

doesn't work becouse you are not compairing numbers but moving them.
You have to use == here so you will get:
1
2
if ((num1 == num2) || (num1 == num3)) mid = num1;
if (num2 == num3) mid = num1;

Note:
You are very redundent with your if-statements. You didn't even notice the thirth statement
of the second line was incorrect. It's probably supposed to be (num3 > num2) but in every
situation that error would show it was already cought with one of the other combinations.
Thanks for the help, especially with the use of ==, and it did lead me to a program I think is correct.

However, I'm not so fond of the condescension at the end. I'm posting in the beginners forum for a reason.
In any case, the second line of my program is a namespace declaration. If I take the line I think you are most likely to mean (line 14) and assume that 'thirth' means third, it is involved in another combination, but either combination would break down if it was removed. The whole point is that that set of combinations exactly covers every circumstance where three different values are entered.
Topic archived. No new replies allowed.