-
Notifications
You must be signed in to change notification settings - Fork 0
/
practice3_4.c
66 lines (52 loc) · 1.22 KB
/
practice3_4.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <stdio.h>
#define MAX(a,b) ((a>b)?a:b)
#define MAX_DEGREE 50
typedef struct polynomial {
int degree;
float coef[MAX_DEGREE];
} polynomial;
polynomial addPoly(polynomial, polynomial);
void printPoly(polynomial);
int main() {
polynomial A = { 3, {4, 3, 5 ,0 } };
polynomial B = { 4, {3, 1, 0 ,2 ,1} };
polynomial C;
C = addPoly(A, B);
printf("\n A(x) = "); printPoly(A);
printf("\n B(x) = "); printPoly(B);
printf("\n C(x) = "); printPoly(C);
getchar();
return 0;
}
polynomial addPoly(polynomial A, polynomial B) {
polynomial C;
int A_index = 0, B_index = 0, C_index = 0;
int A_degree = A.degree;
int B_degree = B.degree;
C.degree = MAX(A.degree, B.degree);
while (A_index <= A.degree && B_index <= B.degree) {
if (A_degree > B_degree) {
C.coef[C_index++] = A.coef[A_index++];
A_degree--;
}
else if (A_degree == B_degree) {
C.coef[C_index++] = A.coef[A_index++] + B.coef[B_index++];
A_degree--;
B_degree--;
}
else {
C.coef[C_index++] = B.coef[B_index++];
B_degree--;
}
}
return C;
}
void printPoly(polynomial P){
int i;
int degree = P.degree;
for (i = 0; i <= P.degree; i++) {
printf("%3.0fx^%d", P.coef[i], degree--);
if (i < P.degree) printf(" +");
}
printf("\n");
}