C++ Example - Finding the Maximum of Three Numbers

C++ Examples

We input three numbers through the screen and find the largest one.

Example - Using if

#include <iostream> using namespace std; int main() { float n1, n2, n3; cout << "Please enter three numbers:"; cin >> n1 >> n2 >> n3; if(n1 >= n2 && n1 >= n3) { cout << "The maximum number is:" << n1; } if(n2 >= n1 && n2 >= n3) { cout << "The maximum number is:" << n2; } if(n3 >= n1 && n3 >= n2) { cout << "The maximum number is:" << n3; } return 0; }

The output of the above program execution 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 << "Please enter three numbers:"; cin >> n1 >> n2 >> n3; if((n1 >= n2) && (n1 >= n3)) cout << "The maximum number is:" << n1; else if ((n2 >= n1) && (n2 >= n3)) cout << "The maximum number is:" << n2; else cout << "The maximum number is:" << n3; return 0; }

The output of the above program execution 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 << "Please enter three numbers:"; cin >> n1 >> n2 >> n3; if (n1 >= n2) { if (n1 >= n3) cout << "The maximum number is:" << n1; else cout << "The maximum number is:" << n3; } else { if (n2 >= n3) cout << "The maximum number is:" << n2; else cout << "The maximum number is:" << n3; } return 0; }

The output of the above program execution is:

请输入三个数,以空格分隔: 2.3
8.3
-4.2
最大数为: 8.3

C++ Examples

other extensions