c언어로 다항식 eval, 가장 큰 차수 제거 구현
이번 코드 역시 학교 과제로 나왔던 문제인데요
피드백 부탁드립니다
#include <stdio.h>
#include <math.h>
#define MAX_DEGREE 20
#define MAX(a,b) (((a)>(b))?(a):(b))
typedef struct {
int degree;
float coef[MAX_DEGREE];
}polynomial;
void Eval(polynomial, double);
polynomial SubtractLO(polynomial A);
int main() {
//문제 2-1
polynomial p = { 5, {10, 0, 0, 0, 6, 1} };
Eval(p, 2);
//문제 2-2
p = SubtractLO(p);
Eval(p, 2);
polynomial p2 = { 5, {5, 0, 0, 4, 0, 2} };
p2 = SubtractLO(p2);
Eval(p2, 2);
polynomial p3 = { 4, {4, 0, 0, 0, 0} };
p3 = SubtractLO(p3);
Eval(p3, 3);
}
void Eval(polynomial A, double num) {
//문제 2-1
double result;
result = 0.0;
for (int i = 0; i <= A.degree; i++)
result += A.coef[i] * pow(num, A.degree-i);
printf("result = %lf\n", result);
}
polynomial SubtractLO(polynomial A) {
//가장 큰 차수를 제거한다.
for(int i = 0; i<=A.degree; i++)
if (A.coef[i] != 0) {
A.coef[i] = 0;
break;
}
//다항식에서 최고차항 계수가 0이 아니게끔 조정하고
//변동이 있을 시에는 degree 값을 바꿔준다.
int notZeroIdx = 0;
char flag = 0;
for (int i = 0; i <= A.degree; i++) {
if (A.coef[i] == 0 && flag == 0) notZeroIdx++;
else {
flag = 1;
A.coef[i - notZeroIdx] = A.coef[i];
}
}
A.degree -= notZeroIdx;
return A;
}
댓글 없음:
댓글 쓰기