编写一个C++程序来查找给定的三个数中的最大数。在下面显示的程序中,我们使用了嵌套的if语句来查找三个数中的最大值。
C++ 程序查找三个数中的最大值
第一个if条件 `if(x – y > 0 && x – z > 0)` 检查 x 是否大于 y 和 z。如果为真,则 x 大于 y。我们在else块内使用了嵌套的If else语句。`if(y – z > 0)` 结果为真,则打印 y 大于 x 和 z。如果上述条件均不满足,则 z 大于 x 和 y。
#include<iostream>
using namespace std;
int main()
{
int x, y, z;
cout << "Please enter the Three Different Number = ";
cin >> x >> y >> z;
if(x - y > 0 && x - z > 0)
{
cout << x << " is Greater Than both " << y << " and " << z;
}
else
{
if(y - z > 0)
{
cout << y << " is Greater Than both " << x << " and " << z;
}
else
{
cout << z << " is Greater Than both " << x << " and " << y;
}
}
return 0;
}
Please enter the Three Different Number = 10 20 1
20 is Greater Than both 10 and 1
x= 44, y= 11, and z= 9
Please enter the Three Different Number = 44 11 9
44 is Greater Than both 11 and 9
x= 88, y= 77, and z= 122
Please enter the Three Different Number =
88
77
122
122 is Greater Than both 88 and 77
使用Else If语句
此程序接受三个值,并使用Else If语句查找三个数中的最大值。
#include<iostream>
using namespace std;
int main()
{
int x, y, z;
cout << "Please enter the Three Different Number = ";
cin >> x >> y >> z;
if (x > y && x > z)
{
cout << x << " is Greater Than both " << y << " and " << z;
}
else if (y > x && y > z)
{
cout << y << " is Greater Than both " << x << " and " << z;
}
else if (z > x && z > y)
{
cout << z << " is Greater Than both " << x << " and " << y;
}
else
{
cout << "Either any two variables are equal or all the three values are equal";
}
return 0;
}
Please enter the Three Different Number = 33 98 122
122 is Greater Than both 33 and 98
在此 C++ 示例中,我们使用了嵌套的条件运算符 `(((x > y && x > z) ? x : (y > z) ? y : z)`。
#include<iostream>
using namespace std;
int main()
{
int x, y, z, largestOfThree;
cout << "Please enter the Three Different Number = ";
cin >> x >> y >> z;
largestOfThree =((x > y && x > z) ? x : (y > z) ? y : z);
cout << "\nLargest number among three is = " << largestOfThree;
return 0;
}
