본문 바로가기
프로그래머스코딩테스트연습풀이/C++

[프로그래머스/C++] 배열의 평균값

by 코코쵸마 2025. 2. 11.

문제

정수 배열 numbers가 매개변수로 주어집니다. numbers의 원소의 평균값을 return하도록 solution 함수를 완성해주세요.

 

솔루션

#include <string>
#include <vector>
#include <numeric>

using namespace std;

double solution(vector<int> numbers) {
    double answer = 0;
    double sum = accumulate(numbers.begin(), numbers.end(), 0);
    return sum / numbers.size();
}

 

https://school.programmers.co.kr/learn/courses/30/lessons/120817

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

 

메모

파이썬에서 sum(arr)으로 썼던 배열의 합을 C++에서 나타내는 방법

1. for문으로 sum+=arr[i]로 for문을 돌려 하나씩 다 더한다

2. accumulate라는 함수를 쓴다. <numeric>이라는 라이브러리에 있는 함수로, accumulate([배열 시작 주소], [배열 끝 주소], [초기값], [연산 함수])

 

배열의 길이를 나타내는 함수로는 numbers.size()를 쓴다.

파이썬에서는 len(numbers)로 썼었다.