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?
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
elseif(c > largest2) largest2 = c;