-
다항식계산 :: 자료구조 실습보고서 01 소스정리필요2 2007. 9. 9. 16:14
#include <stdio.h>
#define MAX_DEGREE 101
#define MAX(a, b) (((a)>(b))? (a):(b))typedef struct {
int degree;
float coef[MAX_DEGREE];
}polynomial;
polynomial poly_add(polynomial A, polynomial B){
polynomial C;
int Apos=0, Bpos=0, Cpos=0;
int degree_a = A.degree;
int degree_b = B.degree;
C.degree = MAX(A.degree, B.degree);while( Apos<=A.degree && Bpos <= B.degree ){
if(degree_a > degree_b){
C.coef[Cpos++] = A.coef[Apos++];
degree_a--;
}
else if(degree_a == degree_b){
C.coef[Cpos++] = A.coef[Apos++] + B.coef[Bpos++];
degree_a--; degree_b--;
}
else{
C.coef[Cpos++] = B.coef[Bpos++];
degree_b++;
}
//printf("%3.2f\n", C.coef[Cpos-1]);
}
return C;
}polynomial poly_sub(polynomial A, polynomial B){
polynomial C;
int Apos=0, Bpos=0, Cpos=0;
int degree_a = A.degree;
int degree_b = B.degree;
C.degree = MAX(A.degree, B.degree);while( Apos<=A.degree && Bpos <= B.degree ){
if(degree_a > degree_b){
C.coef[Cpos++] = A.coef[Apos++];
degree_a--;
}
else if(degree_a == degree_b){
C.coef[Cpos++] = A.coef[Apos++] - B.coef[Bpos++];
degree_a--; degree_b--;
}
else{
C.coef[Cpos++] = B.coef[Bpos++];
degree_b++;
}
//printf("%3.2f\n", C.coef[Cpos-1]);
}
return C;
}void view_poly(polynomial C){
int i;
for(i=C.degree; i>=0;i--){
if(i==0)
{
printf("%3.1f\n", C.coef[C.degree-i]);
}
else
{
printf("%3.1fX^%d + ", C.coef[C.degree-i], i);
}
}
}
void main(void){polynomial A = {3, {4, 3, 2, 1}}, B = {1, {3, 3}}, C;
C = poly_add(A, B);view_poly(C);
C = poly_sub(A, B);
view_poly(C);
}