7-6 一元多项式求导(20 分)
设计函数求一元多项式的导数。
输入格式:
以指数递降方式输入多项式非零项系数和指数(绝对值均为不超过1000的整数)。数字间以空格分隔。
输出格式:
以与输入相同的格式输出导数多项式非零项的系数和指数。数字间以空格分隔,但结尾不能有多余空格。
第一种解法,比较简洁:关键在于数据的读入:while(~scanf("%d%d",&xi,&zhi))
flag还用来确定是不是题目里所谓的“零多项式”。如果是就输出0 0。
<textarea readonly ="readonly" name ="code" class="c++">#include <stdio.h>
int main()
{
int xi,zhi;
int flag=0;
while(~scanf("%d%d",&xi,&zhi))
{
if(zhi==0) continue;
else
{
if(flag==0)
{
printf("%d %d",xi*zhi,zhi-1);
flag=1;
}
else
{
printf(" %d %d",xi*zhi,zhi-1);
}
}
}
if(flag==0) printf("0 0");
return 0;
}</textarea>
第二种解法(单链表):虽然比较繁琐,但是笔者认为可行。可惜数据的读入read()函数代码有问题,在此先记录下代码,日后再解决。
<textarea readonly ="readonly" name ="code" class="c++">#include <stdio.h>
#include <stdlib.h>
struct node{
int x;
int z;
struct node *next;
};
typedef struct node* List;
List read()
{
List head,t;
head=(List)malloc(sizeof(struct node));
head->next=NULL;
t=head;
int xi,zhi;
while(scanf("%d %d",&xi,&zhi)!=EOF)
{
List q;
q=(List)malloc(sizeof(struct node));
q->x=xi;
q->z=zhi;
t->next=q;
q->next=NULL;
}
return head;
}
List qiudao(List L)
{
List q=L->next;
while(q)
{
q->x=(q->x)*(q->z);
q->z=(q->z)-1;
}
return L;
}
void print(List L)
{
List temp=L->next;
while(temp)
{
printf("%d %d",temp->x,temp->z);
if(temp->next) printf(" ");
}
}
int main()
{
List L;
L=(List)malloc(sizeof(struct node));
L=read();
qiudao(L);
print(L);
return 0;
} </textarea>
关键词:scanf()函数的应用;在此挂一个链接:
百度关于scanf()的介绍