Q) 초항이 1이고, 공차가 3인 등차수열의 10개 항을 출력하고, 항들의 합과 평균을 계산하여 출력하는 프로그램을 작성하라.
참고: 등차수열의 일반항은 다음 공식으로 구한다.
a(n) = a(0) + d * n
A) 이와 같이 특정한 규칙에 의하여 생성되는 값을 컨테이너에 할당하는 경우는
generate 알고리듬을 사용하면 됩니다. 또한 합을 구할때는 accumulate 알고리듬을 사용합니다.
//---------------------------------------------------------------------------
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
#include <iterator>
//---------------------------------------------------------------------------
using namespace std;
// 수열의 일반항을 구하는 사용자 정의 함수 객체(user-defined function object)
class arith_series: public unary_function<double, double>
{
public:
arith_series(double first_term, double diff, double term):
a0(first_term), d(diff), n(term) {}
double operator()(double term) { return a0 + d * n++; }
private:
double a0, d, n;
};
int main()
{
const double a0 = 1.0, d = 3.0;
const int num_terms = 10;
vector<double> v_arith_series(num_terms);
generate(v_arith_series.begin(), v_arith_series.end(), arith_series(a0, d, 0));
// arith_series 함수 객체의 호출은 함수 호출과 동일한 형태임에 유의하세요.
copy(v_arith_series.begin(), v_arith_series.end(),
ostream_iterator<double>(cout, " "));
double sum = accumulate(v_arith_series.begin(), v_arith_series.end(), 0),
average = sum / num_terms;
cout << "\nSum = " << sum << ", Average = " << average << endl;
return 0;
}
//---------------------------------------------------------------------------
결과는 물론 다음과 같습니다.
1 4 7 10 13 16 19 22 25 28
Sum = 145, Average = 14.5
|