|
궁그메끄츤오딘가 님이 쓰신 글 :
: 복소수 연산 이거든여 실수부와 허수부의 값을 1.몇개 받을지 스캔하고
: 2.갯수만큼 반복으로 스캔하고
: 3.받은 값들의 연산(+,-,*,/)을 받은개수-(1개)입력하여
: 4출력
ANSI C++ 표준 라이브러리에는 복소수 연산 클래스인 complex가 이미 들어있습니다.
double, float, int와 같은 기본 타입과 동일한 방법으로 계산하고 입출력하면 됩니다.
다음은 complex를 사용한 예제입니다.
complex<double> 대신 그냥 double을 사용한 예제로도 간단하게 고칠 수 있습니다.
//---------------------------------------------------------------------------
#include <iostream>
#include <string>
#pragma hdrstop
#include <complex>
#include <vector>
#include <algorithm>
//---------------------------------------------------------------------------
using namespace std;
template <typename T>
class accumulate_operators
: public unary_function<T, void>
{
public:
accumulate_operators(const string& operators, T init)
: _operators(operators), i(0), lhs(init) {}
void operator()(const T& rhs)
{
switch (_operators[i++]) {
case '+': lhs += rhs; break;
case '-': lhs -= rhs; break;
case '*': lhs *= rhs; break;
case '/': lhs /= rhs;
}
}
T result() { return lhs; }
private:
string _operators;
int i;
T lhs;
};
int main()
{
int num_operands;
cout << "입력할 복소수의 갯수는? "; cin >> num_operands;
cout << endl << num_operands
<< "개의 복소수들을 (실수, 허수) 형식으로 입력하세요.\n"
"복소수 사이는 공백이나 엔터로 구분하세요.\n";
typedef complex<double> dcomplex;
vector<dcomplex> operands(num_operands);
for (int i = 0; i < num_operands; ++i)
cin >> operands[i];
int num_operators = operands.size() - 1;
cout << endl
<< num_operators << "개의 사칙 연산자(+-*/)를 공백없이 붙여서 입력하세요.\n"
<< num_operators << "개가 넘는 문자는 무시합니다.\n";
string operators;
cin >> operators;
cout << for_each(operands.begin() + 1, operands.end(),
accumulate_operators<dcomplex>(operators,
*operands.begin())).result()
<< endl;
return 0;
}
//---------------------------------------------------------------------------
출력 결과는 다음과 같습니다.
---------------------------------------------------------------------------
입력할 복소수의 갯수는? 5
5개의 복소수들을 (실수, 허수) 형식으로 입력하세요.
복소수 사이는 공백이나 엔터로 구분하세요.
(10,9)
(8,7)
(6,5)
(4,3)
(2,1)
4개의 사칙 연산자(+-*/)를 공백없이 붙여서 입력하세요.
4개가 넘는 문자는 무시합니다.
+-*/
(22,29)
|