본문 바로가기

C++

Polynomial with struct

<소스 코드>

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
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#define MAX_DEGREE 101 // 다항식의 최대차수 + 1
 
typedef struct {
    int degree;
    float coef[MAX_DEGREE];
}polynomial;
 
polynomial a = { 5, {1000063} };
 
int MAX(int a, int b) {
    if (a > b)
        return a;
    else
        return b;
}
 
// 구조체 함수
polynomial poly_add1(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--;
        }
    }
    return C;
}
 
void print_poly(polynomial p) {
    // %3.1f : 전체 너비 3칸, 소수점 이하 자릿수를 1자리로 설정
    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) {
    polynomial a = { 5,{ 3600010 } };
    polynomial b = { 4,{ 70501 } };
    polynomial c;
    print_poly(a);
    print_poly(b);
    c = poly_add1(a, b);
    printf("---------------------------------------------------- - \n");
    print_poly(c);
    return 0;
}
cs

 

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
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#define MAX_TERMS 101 // 다항식의 최대차수 + 1
 
struct {
    float coef;
    int expon;
}terms[MAX_TERMS] = { {8,3},{7,1},{1.0},{10,3},{3,2},{1,0} };
int avail = 6;
 
char compare(int a, int b) {
    if (a > b)
        return '>';
    else if (a == b)
        return '=';
    else
        return '<';
}
 
void attach(float coef, int expon) {
    if (avail > MAX_TERMS)
        exit(1);
 
    // 끝에 ++ 더해줘야한다. 이거 절었던 기억이 있다..
    terms[avail].coef = coef;
    terms[avail++].expon = expon;
}
 
cs

 

'C++' 카테고리의 다른 글

포인터 사용법  (0) 2024.10.29