求三个数中最大数的 C++ 程序
在本文中,我们使用 C++ 中的 if、if else 和嵌套 if else 语句在三个数字中找到最大的数字。
要理解此示例,您应该具备以下 C++ 编程 主题的知识:
在这个程序中,用户被要求输入三个数字。
然后这个程序在用户输入的三个数字中找出最大的数字并用正确的消息显示它。
现在我们使用多种方法实现了这个程序。
示例 1:使用 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 << "Largest number: " << n1;
if(n2 >= n1 && n2 >= n3)
cout << "Largest number: " << n2;
if(n3 >= n1 && n3 >= n2)
cout << "Largest number: " << n3;
return 0;
}
输出
Enter three numbers: 2.3
8.3
-4.2
Largest number: 8.3
示例 2:使用 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 << "Largest number: " << n1;
else if ((n2 >= n1) && (n2 >= n3))
cout << "Largest number: " << n2;
else
cout << "Largest number: " << n3;
return 0;
}
输出
Enter three numbers: 2.3
8.3
-4.2
Largest number: 8.3
示例 3:使用嵌套 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 << "Largest number: " << n1;
else
cout << "Largest number: " << n3;
}
else {
if (n2 >= n3)
cout << "Largest number: " << n2;
else
cout << "Largest number: " << n3;
}
return 0;
}
输出
Enter three numbers: 2.3
8.3
-4.2
Largest number: 8.3