문제
정수 배열 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)로 썼었다.
'프로그래머스코딩테스트연습풀이 > C++' 카테고리의 다른 글
[프로그래머스/C++] 양꼬치 (0) | 2025.02.11 |
---|---|
[프로그래머스/C++] 각도기 (0) | 2025.02.11 |
[프로그래머스/C++] 나이 출력 (0) | 2025.02.10 |
[프로그래머스/C++] 숫자 비교하기 (0) | 2025.02.10 |
[프로그래머스/C++] 두 수의 차 (0) | 2025.02.10 |