C++ Example - Largest of Three Numbers
We enter three numbers via the screen and find the largest number.
Example - using if
include
<
iostream
using
namespace
std;
int
main
(
)
{
float
n1
,
n2
,
n3
;
cout
<<
"
Enter three numbers:
"
;
cin
n1
n2
n3
;
if
(
n1
=
n2
&&
n1
=
n3
)
{
cout
<<
"
The largest number is:
"
<<
n1
;
}
if
(
n2
=
n1
&&
n2
=
n3
)
{
cout
<<
"
The largest number is:
"
<<
n2
;
}
if
(
n3
=
n1
&&
n3
=
n2
)
{
cout
<<
"
The largest number is:
"
<<
n3
;
}
return
0
;
}
The output of the above program is:
请输入三个数: 2.3
8.3
-4.2
最大数为: 8.3
Example - using if...else
include
<
iostream
using
namespace
std;
int
main
(
)
{
float
n1
,
n2
,
n3
;
cout
<<
"
Enter three numbers:
"
;
cin
n1
n2
n3
;
if
(
(
n1
=
n2
)
&&
(
n1
=
n3
)
)
cout
<<
"
The largest number is:
"
<<
n1
;
else
if
(
(
n2
=
n1
)
&&
(
n2
=
n3
)
)
cout
<<
"
The largest number is:
"
<<
n2
;
else
cout
<<
"
The largest number is:
"
<<
n3
;
return
0
;
}
The output of the above program is:
请输入三个数,以空格分隔: 2.3
8.3
-4.2
最大数为: 8.3
Example - using nested if...else
include
<
iostream
using
namespace
std;
int
main
(
)
{
float
n1
,
n2
,
n3
;
cout
<<
"
Enter three numbers:
"
;
cin
n1
n2
n3
;
if
(
n1
=
n2
)
{
if
(
n1
=
n3
)
cout
<<
"
The largest number is:
"
<<
n1
;
else
cout
<<
"
The largest number is:
"
<<
n3
;
}
else
{
if
(
n2
=
n3
)
cout
<<
"
The largest number is:
"
<<
n2
;
else
cout
<<
"
The largest number is:
"
<<
n3
;
}
return
0
;
}
The output of the above program is:
请输入三个数,以空格分隔: 2.3
8.3
-4.2
最大数为: 8.3
C++ Example