Can't find largest number

When I run this code, it always tells me the largest number is the first one inputed. Why is that?
I know there is a more efficient way to do this with an array, but my teacher doesn't want us to for this lab.
Thank you!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <cmath>
using namespace std;

int main()
{
	int num1, num2, num3, largest;
	cout << "Please enter three numbers, separated by commas." << endl;
	cin >> num1, num2, num3 ;
	if ((num1>num2) and (num1>num3))
	{
	largest=num1;
	}
	else if ((num2>num1) and (num2>num3))
	{
	largest=num2;
	}
	else if ((num3>num1) and (num3>num2))
	{
	largest=num3;
	}
	cout << "Thank you. The largest of the three is " << largest << endl;
	return 0;
	
	
	
	
	
}
The best way is to learn to debug your own code. I put in some comments to help.
Run it and see if you can find the problem.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <cmath>
using namespace std;

int main()
{
	int num1=0, num2=0, num3=0, largest=0;
	cout << "Please enter three numbers, separated by commas." << endl;
	cin >> num1, num2, num3 ;
	cout << num1 << " " << num2 << " " << num3 << endl;
	if ((num1>=num2) && (num1>=num3))
		{
		largest=num1;
		cout << "Test1" << endl;
		}
	else if ((num2>=num1) && (num2>=num3))
		{
		largest=num2;
		cout << "Test2" << endl;
		}
	else if ((num3>=num1) && (num3>=num2))
		{
		largest=num3;
		cout << "Test3" << endl;
		}
		
	cout << "Thank you. The largest of the three is " << largest << endl;
	
	return 0;
}
Last edited on
Why do the variables need to be set equal to zero? I changed the code around, but still getting the first number and always being the greatest.
Just for case you are interested in my solution. I needed to find out the min and max:
float R, G, B,min, max;
set your values ... and then use this:
1
2
min = (B < G) ? ((R < B) ? R : B) : (R < G ? R : G);
max = (B > G) ? ((R > B) ? R : B) : (R > G ? R : G);


This should be the same:
1
2
min = B < G ? (R < B ? R : B) : (R < G ? R : G);
max = B > G ? (R > B ? R : B) : (R > G ? R : G);


1
2
min = B < G ? R < B ? R : B : R < G ? R : G;
max = B > G ? R > B ? R : B : R > G ? R : G;


It looks odd but is very short.
Last edited on
Topic archived. No new replies allowed.