题目
【问题描述】
编写一个程序实现两个一元多项式相乘。
【输入形式】
首先输入第一个多项式中系数不为0的项的系数和指数,以一个空格分隔。且该多项式中各项的系数均为0或正整数,系数和最高幂次不会超过int类型的表示范围。对于多项式的输入方法如下:
an n a n-1 n-1 … a1 1 a0 0
即相邻两个整数分别表示表达式中一项的系数和指数。在输入中只出现系数不为0的项。最后一项的指数后没有空格,只有一个回车换行符。
按照上述方式再输入第二个多项式。
【输出形式】
将运算结果输出到屏幕。将系数不为0的项按指数从高到低的顺序输出,每次输出其系数和指数,均以一个空格分隔,最后一项的指数后也可以有一个空格。
【样例输入】
10 80000 2 6000 7 300 5 10 18 0
3 6000 5 20 8 10 6 0
【样例输出】
30 86000 50 80020 80 80010 60 80000 6 12000 21 6300 10 6020 31 6010 66 6000 35 320 56 310 42 300 25 30 130 20 174 10 108 0
提示:利用链表存储多项式的系数和指数。
问题
笔者(C语言初学者)根据现有知识通过结构体编程,但发现其中部分模块出现问题,根据调试观察,问题出在函数内的参数地址问题,笔者不清楚函数参数如何改变并返回。下面附上代码,其中函数cal是问题所在。
#include<stdio.h>
#include<malloc.h>
typedef struct list
{
int coe;
int sub;
struct list* next;
}num;
void cal(num* head,num* turn, num* end);
void order(num* head, num* end);
void print(num* head, num* end);
int main()
{
int ch;
int coe, sub;
num* p = NULL;
num* turn = NULL;
num* node = NULL;
num* head = NULL;
num* end = NULL;
do
{
scanf_s("%d %d", &coe, &sub);
p = (num*)malloc(sizeof(num*));
if (head == NULL)
head = p;
else
{
node->next = p;
}
if(p)
{
p->coe = coe;
p->sub = sub;
}
node = p;
} while ((ch = getchar()) != '\n');
turn = node;
do
{
scanf_s("%d %d", &coe, &sub);
p = (num*)malloc(sizeof(num*));
if(p&&node)
{
node->next = p;
p->coe = coe;
p->sub = sub;
}
node = p;
} while ((ch = getchar()) != '\n');
end = node;
cal(head,turn,end);
order(head,end);
print(head,end);
return 0;
}
void cal(num* head,num* turn, num* end)
{
num* p = NULL;
num* p1 = head;
num* p2 = turn;
int i=0;
int j = 0;
do
{
p2 = turn;
if (i==1)
{
p1 = p1->next;
}
i = 1;
do
{
p2 = p2->next;
p = (num*)malloc(sizeof(num*));
if(j==0)
{
head = p;
j = 1;
}
if(p)
{
p->coe = p1->coe * p2->coe;
p->sub = p1->sub * p2->sub;
}
}while (p2 != end);
} while (p1 != turn);
end = p;
}
void order(num* head, num* end)
{
num* p1 = head;
num* p2 = head;
num* p3 = head;
int i;
int j=0;
int q= 0;
do
{
if (j == 1)
{
p1 = p1->next;
p2 = p1;
p3 = p1;
}
j = 1;
q = 0;
do
{
if (q == 1)
{
p3 = p3->next;
}
p2 = p3->next;
q = 1;
if (p1->sub < p2->sub)
{
i = p1->sub;
p1->sub = p2->sub;
p2->sub = i;
}
if (p1->sub == p2->sub)
{
p1->coe += p2->coe;
if(p2!=end)
{
p3->next = p2->next;
}
else
{
end = p3;
}
}
} while (p2 != end);
} while (p1 != end);
}
void print(num* head, num* end)
{
num* p = head;
int i = 0;
do
{
if (i == 1)
{
p = p->next;
}
i = 1;
printf("%d %d ", p->coe, p->sub);
} while (p != end);
}