C++ 实例 - 判断三个数中的最大数
通过屏幕我们输入三个数字,并找出最大的数。
实例 - 使用 if
#include <iostream>
using namespace std;
int main()
{
float n1, n2, n3;
cout << "请输入三个数: ";
cin >> n1 >> n2 >> n3;
if(n1 >= n2 && n1 >= n3)
{
cout << "最大数为: " << n1;
}
if(n2 >= n1 && n2 >= n3)
{
cout << "最大数为: " << n2;
}
if(n3 >= n1 && n3 >= n2) {
cout << "最大数为: " << n3;
}
return 0;
}
以上程序执行输出结果为:
请输入三个数: 2.3 8.3 -4.2 最大数为: 8.3
实例 - 使用 if...else
#include <iostream>
using namespace std;
int main()
{
float n1, n2, n3;
cout << "请输入三个数: ";
cin >> n1 >> n2 >> n3;
if((n1 >= n2) && (n1 >= n3))
cout << "最大数为: " << n1;
else if ((n2 >= n1) && (n2 >= n3))
cout << "最大数为: " << n2;
else
cout << "最大数为: " << n3;
return 0;
}
以上程序执行输出结果为:
请输入三个数,以空格分隔: 2.3 8.3 -4.2 最大数为: 8.3
实例 - 使用内嵌的 if...else
#include <iostream>
using namespace std;
int main()
{
float n1, n2, n3;
cout << "请输入三个数: ";
cin >> n1 >> n2 >> n3;
if (n1 >= n2)
{
if (n1 >= n3)
cout << "最大数为: " << n1;
else
cout << "最大数为: " << n3;
}
else
{
if (n2 >= n3)
cout << "最大数为: " << n2;
else
cout << "最大数为: " << n3;
}
return 0;
}
以上程序执行输出结果为:
请输入三个数,以空格分隔: 2.3 8.3 -4.2 最大数为: 8.3
C++ 实例
麻言
hi.***gwei@qq.com
可以使用临时变量记录最大值:
#include <iostream> using namespace std; int main() { float n1, n2, n3, max; cout << "请输入三个数: "; cin >> n1 >> n2 >> n3; if(n1 >= n2) { max = n1; }else{ max = n2; } if(n3 >= max) { max = n3; } cout << "最大数为: " << max; return 0; }麻言
hi.***gwei@qq.com
Alee
dro***am@163.com
参考方法:
#include <iostream> using namespace std; int main(int argc, char *argv[]) { float a,b,c,MAX; cout << "请输入三个数, 用空格隔开" << endl; cin >> a >> b >> c; MAX = a > b ? a : b; MAX = MAX > c ? MAX : c; cout <<"最大数是 " << MAX; return 0; }Alee
dro***am@163.com
可可爱爱没有脑袋
177***7913@qq.com
只使用三目运算符,不用临时变量:
#include <iostream> using std::cin; using std::cout; using std::endl; int main() { float num1,num2,num3; cout<<"请输入三个数:"<<endl; cin>>num1>>num2>>num3; cout<<"三个数中的最大数为:"; num1>num2?(num1>num3?cout<<num1:cout<<num3):(num2>num3?cout<<num2:cout<<num3); return 0; }可可爱爱没有脑袋
177***7913@qq.com