在此程序中,用户被要求输入三个数字。
然后,此程序找出用户输入的三个数字中最大的一个,并显示出来,附带一条恰当的消息。
此程序可以有多种编写方式。
示例 1:使用 if...else 语句查找最大数
#include <iostream>
using namespace std;
int main() {
double n1, n2, n3;
cout << "Enter three numbers: ";
cin >> n1 >> n2 >> n3;
// check if n1 is the largest number
if(n1 >= n2 && n1 >= n3)
cout << "Largest number: " << n1;
// check if n2 is the largest number
else if(n2 >= n1 && n2 >= n3)
cout << "Largest number: " << n2;
// if neither n1 nor n2 are the largest, n3 is the largest
else
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() {
double n1, n2, n3;
cout << "Enter three numbers: ";
cin >> n1 >> n2 >> n3;
// check if n1 is greater than n2
if (n1 >= n2) {
// if n1 is also greater than n3,
// then n1 is the largest number
if (n1 >= n3)
cout << "Largest number: " << n1;
// but if n1 is less than n3
// but n1 is greater than n2
// then n3 is the largest number
else
cout << "Largest number: " << n3;
}
// else, n2 is greater than n1
else {
// if n2 is also greater than n3,
// then n2 is the largest number
if (n2 >= n3)
cout << "Largest number: " << n2;
// but if n2 is less than n3
// but n2 is greater than n1
// then n3 is the largest number
else
cout << "Largest number: " << n3;
}
return 0;
}
输出
Enter three numbers: 2.3 8.3 -4.2 Largest number: 8.3
另请阅读