Adding issue

I'm having a problem with a program which adds a highest number and a 2nd highest number...

I have this code so far...


The Cin statements go here...

Largest number here....

middle number here:
{
if (num1 > largest)
largest2 = num1;
else
largest2 = num2;
}

{
if (num3 > largest)
largest2 = num3;
}

The sum equation and the Cout goes down here... obviously

Now what's happening is that it adds the num2 and the largest... I need it to add the largest and the second largest... not num2 and largest. WHat did I do wrong here?
Last edited on
if i enter 8, 12 and 1, it adds 8 and 12... no issues there

if i enter 4, 11 and 17... it adds the 11 and the 17... no issues there either

however if i enter 18, 1 and 13 it will add the 18 and the 1, while missing the 13.

what is going on here? i know it's a teeny error somewhere.
Consider inputs 2, 1, 3. After the first two ifs largest = 3. No number of the three is larger than 3 (since it is the largest) so 3rd and 4th ifs fail and due to the else condition in 3rd if, largest2 = num2.

One thing you could do is use the fact that if A is largest, B is second largest and C is smallest, A+B = A+B+C-C. You know A+B+C and C is easier to find than A and B.

If you want to do it the normal way, I guess it would be better to always keep track of largest and largest2. That is,
1
2
3
4
5
if(a > b) largest = a, largest2 = b;//assign the larger to largest
else largest = b, largest2 = a;//and don't leave largest2 without a value.

if(c > largest) largest2 = largest, largest = c;//largest becomes 2nd largest
else if(c > largest2) largest2 = c;
(code not tested)
Last edited on
Ok, I got it through another way, through the use of:

if (num1>=num3 && num3>=num2 || num1<=num3 && num3<=num2)

and a few more lines similar, before and after and now it works as I want it to do after desk checking.

Thanks.
Topic archived. No new replies allowed.