标签:
设计函数求一元多项式的导数。(注:xn(n为整数)的一阶导数为n*xn-1。)
输入格式:以指数递降方式输入多项式非零项系数和指数(绝对值均为不超过1000的整数)。数字间以空格分隔。
输出格式:以与输入相同的格式输出导数多项式非零项的系数和指数。数字间以空格分隔,但结尾不能有多余空格。注意“零多项式”的指数和系数都是0,但是表示为“0 0”。
输入样例:
3 4 -5 2 6 1 -2 0
输出样例:
12 3 -10 1 6 0
#include<stdio.h> #include<stdlib.h> typedef struct polynomial{ int Coeff; int Exp; struct polynomial *Next; }poly; poly *CreatNode(); void Insert(poly *head); void derivation(poly *head); void PrintList(poly *head); int main() { poly *l = CreatNode(); Insert(l); derivation(l); PrintList(l); return 0; } poly *CreatNode() { poly *head; head = (poly *)malloc(sizeof(poly)); head ->Coeff = 0; head ->Exp = 0; head ->Next = NULL; return head; } void Insert(poly *head) { poly *p ,*l; int temp; l = head; do{ p = CreatNode(); scanf("%d",&temp); p ->Coeff = temp; scanf("%d",&temp); p ->Exp = temp; l ->Next = p; l = l->Next; }while(temp = getchar() != ‘\n‘); } void derivation(poly *head) { poly *current,*prev; current = prev = head; while(current -> Next != NULL) { prev = current; current = current ->Next; if(head->Next -> Exp ==0 && head->Next ->Next ==NULL) //只有一个常数项 { current ->Coeff = 0; } else if(current ->Coeff ==0 && current ->Exp ==0) { ; } else if(current ->Exp == 0) { prev ->Next = current -> Next; free(current); current = prev; } else{ current ->Coeff = current ->Coeff * current ->Exp; current -> Exp = current ->Exp - 1; } } } void PrintList(poly *head) { poly *p = head ->Next; if(p != NULL) { while(p ->Next != NULL) { printf("%d %d ",p->Coeff,p->Exp); p = p ->Next; } printf("%d %d",p->Coeff,p->Exp); } }
做题时遇到的问题有
开始时想用结构数组实现,但是当时没想到删除某一项数组的方法。改为用链表实现。
求导过程中的关键
只有一个常数项时输出[0 0],对[3 4 5 0]求导时 应输出[12 3]
Coeff = 0 or Exp =0
“零多项式”的指数和系数都是0,但是表示为“0 0”
create一个指针p时应该先分配空间再prev->next = p,如果声明指针后就prev->next = p 得到的结果是 Prev ->next == NULL!!!!!
//错误的代码
void Insert(poly *head) { poly *p = head->Next; int temp; do{ if(p == NULL) { p = CreatNode(); } scanf("%d",&temp); p ->Coeff = temp; scanf("%d",&temp); p ->Exp = temp; p = p->Next; }while(temp = getchar() != ‘\n‘); }
标签:
原文地址:http://www.cnblogs.com/yangRyoung/p/4626386.html