Skip to content

7. 関数

7.Q Max of Three(★☆☆) ​

問題 ​

整数が与えられる。を引数に取り、最大値を返す関数max_of_threeを作ろう。

次のプログラムの// ここにプログラムを書くの部分に、関数max_of_threeを定義して完成させること。main関数のコードは変更しないこと。

cpp
#include <iostream>
using namespace std;

// ここにプログラムを書く

int main() {
    int a, b, c;
    cin >> a >> b >> c;
    cout << max_of_three(a, b, c) << endl;
}

入出力例 ​

例1 ​

入力 ​

Input
3 9 4

出力 ​

Output
9

例2 ​

入力 ​

Input
-5 -2 -10

出力 ​

Output
-2

ヒント ​

ヒント1

if文で最大値を更新する方法が使えます。

ヒント2

最初にxを最大値としておき、yやzと比較していくと簡単です。

解答例 ​

解答例
cpp
#include <iostream>
using namespace std;

int max_of_three(int x, int y, int z) {
    int best = x;
    if (y > best) {
        best = y;
    }
    if (z > best) {
        best = z;
    }
    return best;
}

int main() {
    int a, b, c;
    cin >> a >> b >> c;
    cout << max_of_three(a, b, c) << endl;
}