首先来看下题目,这是一道简单的编程题
这里写出几种常见解法,供大家参考。
解法1:
#include <bits/stdc++.h>
using namespace std;
int main()
{
int a, b, c;
cin >> a >> b >> c;
if (a >= b && a >= c) //&&表示“与”关系,两个关系同时满足时输出结果
cout << a;
if (b >= a && b >= c)
cout << b;
if (c >= a && c >= b)
cout << a;
return 0;
}
上面这种写法中规中矩,可读性强,但是摒弃了优雅。
解法2:
下面这种写法借助max变量,将比较的过程简化了。
#include <bits/stdc++.h>
using namespace std;
int main()
{
int a, b, c;
cin >> a >> b >> c;
int max = a;
if (b > max)
max = b;
if (c > max)
max = c;
cout << max;
return 0;
}
解法3:
下面这种做法应该是最简短的求三个数最大值的了,其实就是把上面你的if简化了。
#include <bits/stdc++.h>
using namespace std;
int main()
{
int a, b, c;
cin >> a >> b >> c;
int max = a;
max = (b > max) ? b : max;
max = (c > max) ? c : max;
cout << max;
return 0;
}
对此题的一些拓展(max_element函数)
这道题求的是三个数的最大值,我们可以通过两次比较来完成,如果求一个数组的最大值呢?我们可以除了通过循环比较来完成,还有更简便的方法吗?答案是有。
咱么可以使用max_element函数来求数组中最大值。PS:需要有数组和指针知识基础。
#include <bits/stdc++.h>
using namespace std;
int main()
{
int arr[5] = {2, 9, 5, 4, 3};//定义一个数组
int *p = max_element(arr, arr + 5);//初地址到末地址
cout << *p;//输出 9
return 0;
}
我是North_Move,我正在学习C++。
欢迎大家关注我的CSDN账号,我会更新有趣的C++基础知识。