题目 1002: [编程入门]三个数最大值(C++语言从简单题中学习最优写法)

 首先来看下题目,这是一道简单的编程题

 这里写出几种常见解法,供大家参考。

解法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++基础知识。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值