[Hackerrank] C++ - 06 Functions

후유카와·2024년 11월 22일

Hackerrank

목록 보기
6/59

06. 함수

[ 난이도: Easy | 분야: Introduction ]

1. 내용 정리

함수라는 것은 여러 구문들을 한데 모아둔 것이다.

return type에 기반하여 아무 것도 반환하지 않거나(void) 어떤 것을 반환한다.

Syntax

return_type function_name(arg_type_1 arg_1, arg_type_2 arg_2, ...) {
	...
    ...
    ...
    [if return_type is non void]
    	return something of type 'return_type';
}

예를 들어, 네 개의 파라미터의 합을 반환한다고 할 때 다음과 같이 코드를 작성할 수 있다.

int sum_of_four(int a, int b, int c, int d) {
	int sum = 0;
    sum += a;
    sum += b;
    sum += c;
    sum += d;
    return sum;
}

2. 과제

최댓값을 반환하는 int max_of_four(int a, int b, int c, int d) 함수를 작성해라.

+= : Add and assignment operator. It adds the right operand to the left operand and assigns the result to the left operand.
a += b is equivalent to a = a + b

입력 형식

입력값은 네 개의 상수를 포함한다. - a, b, c, d, 각 문자는 한 줄에 하나씩 들어 있다.

출력 형식

네 개의 상수 중 가장 큰 수를 반환해라.

참조: 입력과 출력은 신경 쓸 필요가 없다.

입력 예시

3
4
5
6

출력 예시

6

문제

#include <iostream>
#include <cstdio>
using namespace std;

/*
Add `int max_of_four(int a, int b, int c, int d)` here.
*/

int main() {
	int a, b, c, d;
    scanf("%d %d %d %d", &a, &b, &c, &d);
    int ans = max_of_four(a,b,c,d);
    printf("%d", ans);
    
    return 0;
}

더보기

정답

#include <iostream>
#include <cstdio>
using namespace std;

/*
Add `int max_of_four(int a, int b, int c, int d)` here.
*/

int max_of_four(int a, int b, int c, int d) {
	int max_num = 0;
    if(a>max_num) max_num = a;
    if(b>max_num) max_num = b;
    if(c>max_num) max_num = c;
    if(d>max_num) max_num = d;
    return max_num;
}

int main() {
	int a, b, c, d;
    scanf("%d %d %d %d", &a, &b, &c, &d);
    int ans = max_of_four(a,b,c,d);
    printf("%d", ans);
    
    return 0;
}

ⓒ Hackerrank. All Rights Reserved.

profile
안녕하세요! 저는 전자공학을 전공하며 하드웨어와 소프트웨어 모두를 깊이 있게 공부하고 있는 후유카와입니다. Verilog HDL, C/C++, Java, Python 등 다양한 프로그래밍 언어를 다루고 있으며, 최근에는 알고리즘에 대한 학습에 집중하고 있습니다. 기술적인 내용을 공유하고, 함께 성장할 수 있는 공간이 되기를 바랍니다. 잘못된 내용이나 피드백은 언제나 환영합니다! 함께 소통하며 더 나은 지식을 쌓아가요. 감사합니다!

0개의 댓글