编写一个 C++ 程序,找出给定两个数中的较大者。在下面编写的 C++ 程序中,我们使用 Else if 语句来找出两个数中的较大者。如果 (x > y),第一个 if 条件检查 x 是否大于 y。如果为真,则 x 大于 y。接下来,else if(y > x) 检查 y 是否大于 x。如果为真,则 y 大于 x。如果以上两个条件都不满足,则两者相等。
#include<iostream>
using namespace std;
int main()
{
int x, y;
cout << "Please enter the Two Different Number = ";
cin >> x >> y;
if(x > y)
{
cout << x << " is Greater Than " << y;
}
else if(y > x)
{
cout << y << " is Greater Than " << x;
}
else
{
cout << "Both are Equal";
}
return 0;
}

C++ 查找两个数中较大者的程序 示例 2
第一个 if 条件检查 x 和 y 是否相等。如果为假,我们则使用条件运算符 ((x > y) ? x : y) 来返回两者中较大的那个。
#include<iostream>
using namespace std;
int main()
{
int x, y, largest;
cout << "Please enter the Two Different Number = ";
cin >> x >> y;
if(x == y)
{
cout << "\nBoth are Equal";
}
else
{
largest = (x > y) ? x : y;
cout << "\nThe Largest value of two Numbers = " << largest;
}
return 0;
}
Please enter the Two Different Number = 89 77
The Largest value of two Numbers = 89
让我尝试一下这个 C++ 程序中的另一个值。
Please enter the Two Different Number = 55 98
The Largest value of two Numbers = 98