以下是使用C语言实现一元多项式加法运算的代码示例:

#include <stdio.h>

#define MAX_TERMS 100

typedef struct {
    float coef;  // 系数
    int exp;     // 指数
} Term;

void add(Term a[], int na, Term b[], int nb, Term c[], int *nc);

int main() {
    int na, nb, nc = 0;
    Term a[MAX_TERMS], b[MAX_TERMS], c[MAX_TERMS];

    printf("Enter the number of terms in polynomial A: ");
    scanf("%d", &na);
    printf("Enter the terms of polynomial A (in the format 'coef exp'): ");
    for (int i = 0; i < na; i++) {
        scanf("%f %d", &a[i].coef, &a[i].exp);
    }

    printf("Enter the number of terms in polynomial B: ");
    scanf("%d", &nb);
    printf("Enter the terms of polynomial B (in the format 'coef exp'): ");
    for (int i = 0; i < nb; i++) {
        scanf("%f %d", &b[i].coef, &b[i].exp);
    }

    add(a, na, b, nb, c, &nc);

    printf("The sum of the polynomials is: ");
    for (int i = 0; i < nc; i++) {
        printf("%.2fx^%d ", c[i].coef, c[i].exp);
        if (i != nc - 1) {
            printf("+ ");
        }
    }
    printf("\n");

    return 0;
}

void add(Term a[], int na, Term b[], int nb, Term c[], int *nc) {
    int i = 0, j = 0, k = 0;

    while (i < na && j < nb) {
        if (a[i].exp > b[j].exp) {
            c[k] = a[i];
            i++;
        } else if (a[i].exp < b[j].exp) {
            c[k] = b[j];
            j++;
        } else {
            c[k].coef = a[i].coef + b[j].coef;
            c[k].exp = a[i].exp;
            i++;
            j++;
        }
        k++;
    }

    while (i < na) {
        c[k] = a[i];
        i++;
        k++;
    }

    while (j < nb) {
        c[k] = b[j];
        j++;
        k++;
    }

    *nc = k;
}

该代码首先定义了一个结构体 Term,用来表示一项多项式,包括系数和指数。然后定义了函数 add,用来实现两个多项式的加法。最后在 main 函数中读入两个多项式的数据,调用 add 函数进行加法运算,并输出结果。

该代码示例展示了如何使用C语言实现一元多项式加法运算,并提供了一个完整的代码框架。你可以根据实际需要对代码进行修改和扩展。

C语言实现一元多项式加法运算

原文地址: https://www.cveoy.top/t/topic/lRG0 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录