int arr[7];
// 4번째 원소 접근 방법 2가지
arr[3] = 613;
*(arr+3) = 613;
다항식 표현
class Polynomial; // 전방 선언
class Term {
friend Polynomial; // Polynomial class에서 접근 가능
private:
float coef; // 계수
int exp; // 지수
};
class Polynomial {
private:
Term *termArray; // 0이 아닌 항의 배열
int capacity; // termArray 크기
int terms; // 0이 아닌 항의 수
public:
void NewTerm(const float theCoeff, const int theExp);
Polynomial(void); // 생성자
~Polynomial(void); // 파괴자
};
다항식 덧셈
Polynomial Polynomial::Add (Polynomial b){
// A(x) + B(x) 반환
Polynomial c;
int aPos = 0; bPos = 0;
while ((aPos<terms) && (bPos<b.terms)) {
// a 지수 < b 지수
if (termArray[aPos].exp < b.termArray[bPos].exp) {
c.NewTerm(b.termArray[bPos].coef, b.termArray[bPos].exp);
bPoss++;
}
// a 지수 > b 지수
else if (termArray[aPos].exp > b.termArray[bPos].exp){
c.NewTerm(termArray[aPos].coef, termArray[aPos].exp);
aPos++;
}
// a 지수 = b 지수
else {
float t = termArray[aPos].coef + b.termArray[bPos].coef;
if (t) // t가 0이 아니면
c.NewTerm(t, termArray[aPos].exp);
aPos++; bPos++;
}
}
// A(x) 남은 항 추가
for (; aPos<terms; aPos++)
c.NewTerm(termArray[aPos].coef, termArray[aPos].exp);
// B(x) 남은 항 추가
for (; bPos<b.terms; bPos++)
c.NewTerm(b.termArray[bPos].coef, b.termArray[bPos].exp);
return c;
}
'알고리즘 > C++' 카테고리의 다른 글
3. 스택 (Stack) (0) | 2020.07.21 |
---|---|
Container Class와 Template (0) | 2020.07.13 |
1. 기본 개념 (0) | 2020.07.12 |
C++ 배열 동적할당 (0) | 2020.06.23 |
C 배열 동적할당 (0) | 2020.06.21 |