c++代码实现创建一元多项式
时间: 2024-03-15 18:37:24 浏览: 83
c语言实现一元多项式
4星 · 用户满意度95%
创建一元多项式的C代码实现可以使用链表来表示多项式。每个节点包含两个成员,一个是存储系数的变量,一个是存储指数的变量。下面是一个简单的创建一元多项式的C代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义多项式的节点结构
struct node {
int coefficient; // 系数
int exponent; // 指数
struct node* next; // 指向下一个节点的指针
};
// 创建多项式的函数
struct node* createPolynomial() {
struct node* polynomial = NULL; // 多项式的头节点
struct node* current = NULL; // 当前节点
// 创建多项式的节点
int coefficient, exponent;
printf("请输入多项式的系数和指数(以-1 -1结束输入):\n");
while (1) {
scanf("%d %d", &coefficient, &exponent);
if (coefficient == -1 && exponent == -1) {
break;
}
struct node* newNode = (struct node*)malloc(sizeof(struct node));
newNode->coefficient = coefficient;
newNode->exponent = exponent;
newNode->next = NULL;
if (current == NULL) {
polynomial = newNode;
current = newNode;
} else {
current->next = newNode;
current = newNode;
}
}
return polynomial;
}
// 打印多项式的函数
void printPolynomial(struct node* polynomial) {
struct node* current = polynomial;
printf("多项式的表达式为:");
while (current != NULL) {
printf("%dx^%d ", current->coefficient, current->exponent);
current = current->next;
if (current != NULL) {
printf("+ ");
}
}
printf("\n");
}
int main() {
struct node* polynomial = createPolynomial();
printPolynomial(polynomial);
return 0;
}
```
阅读全文