다항식f(x) = x^100 + x^2 + 1g(x) = x^1000 + 2일 때,
f(x) + g(x) = 를 계산하는 프로그램을 만드시오.
단, 아래 조건을 만족해야함
- 다항식을 표현하는 Poly 구조체를 만들고
- main 함수에서 Poly f, Poly g, Poly result; 를 선언하고
- result = add_poly(f, g); 코드를 통해서 합을 만들고
- print_poly() 함수로 결과 출력
// 위 조건을 만족하는 코드의 예시.
int main() { Poly f; Poly g; Poly result; // f, g, 값 설정 코드... result = add_poly(f, g); print_poly(result); return 0; }
#include <stdio.h>
#define MAX(a,b)(((a)>(b))?(a):(b))
#define MAX_DEGREE 10001//다항식의 최대차수+1
typedef struct {
int degree;
float coef[MAX_DEGREE];
}Poly;
Poly poly_add1(Poly A, Poly B) { //{ 5, { 3, 6, 0, 0, 0, 10 } } , // { 4,{ 7, 0, 5, 0, 1 } }
Poly C;
int Apos = 0, Bpos = 0, Cpos = 0; //배열 인덱스 변수
int degree_a = A.degree;//5
int degree_b = B.degree;//4
C.degree = MAX(A.degree, B.degree);
while (Apos <= A.degree&&Bpos <= B.degree)//A인덱스가 A차수보다 작거나 같을 때,그리고 B인덱스가 B 차수보다 작거나 같을때 반복
{
if (degree_a > degree_b) {//A차수가 b 차수보다 클때
C.coef[Cpos++] = A.coef[Apos++];//C차수의 인덱스의 숫자는 1증가 <=A차수의 인덱스의 숫자는 1증가
degree_a--;//A차수 1감소
}
else if (degree_a == degree_b) {//A차수와 B차수가 같다면
C.coef[Cpos++] = A.coef[Apos++] + B.coef[Bpos++]; //C차수의 인덱스의 숫자는 1증가하고 <= A차수의 배열과 B차수 배열 더한다.
degree_a--; degree_b--;//차수 A,B감소
}
else {//B차수가 A차수보다 클때
C.coef[Cpos++] = B.coef[Bpos++];//배열 C는 증가=배열 B도 증가
degree_b--;//b의 차수는 감소
}
}
return C;//결과 값 리턴
}
void print_poly(Poly p)
{
for (int i = p.degree; i > 0; i--)
printf("%3.1fx^%d + ", p.coef[p.degree - i], i);
printf("%3.1f \n", p.coef[p.degree]);
}
int main(void){
Poly f = { 5,{ 3, 6, 0, 0, 0, 10 } };//차수, 값
Poly g = { 4,{ 7, 0, 5, 0, 1 } };//차수, 값
Poly result;
print_poly(f);
print_poly(g);
result = poly_add1(f,g);
printf("---------------------------------\n");
print_poly(result);
return 0;
}