设为首页 加入收藏

TOP

c语言实现一元多项式(一)
2013-07-22 17:54:06 来源: 作者: 【 】 浏览:228
Tags:语言 实现 一元 多项

  [cpp]

  /*

  * Ploly.c

  *

  *  Created on: 2012-12-3

  *      Author: Administrator

  */

  #include <stdio.h>

  #include <stdlib.h>

  #define DEV 0.0000002

  #define TRUE 1

  #define OK 1

  #define ERROR 0 

  #define CHECK(t) do{if(!(t)){return 0;}}while(0)

  typedef int Status;

  typedef struct term {

  double coef;

  int expn;

  struct term *next;

  } PolyNode, *Poly;

  Status makeNode(double coef, int expn, Poly *p) {

  (*p) = (Poly) malloc(sizeof(struct term));

  CHECK(*p);

  (*p)->coef = coef;

  (*p)->expn = expn;

  (*p)->next = 0;

  return OK;

  }

  Status destoryPoly(Poly *head) {

  Poly p = *head;

  while (p) {

  *head = p->next;

  free(p);

  p = *head;

  }

  *head = 0;

  return OK;

  }

  Status AddNodePoly(Poly *head, double coef, int expn) {

  CHECK(*head);

  if (abs(coef) < DEV)

  return OK;

  Poly q = (*head)->next;

  Poly p = (*head);

  Poly s;

  while (q && expn < q->expn) {

  p = q;

  q = q->next;

  }

  if (q == 0 || expn > q->expn) {

  CHECK(makeNode(coef, expn,&s));

  p->next = s;

  s->next = q;

  } else {

  q->coef += coef;

  if (q->coef == 0) {

  p->next = q->next;

  free(q);

  }

  }

  return OK;

  }

  Status createPoly(Poly *head) {

  if (*head)

  destoryPoly(head);

  CHECK(makeNode(0,0,head));

  int expn;

  double coef;

  do {

  scanf("%lf%d", &coef, &expn);

  if (abs(coef) < DEV && expn == 0)

  break;

  if (abs(coef) < DEV

  )

  continue;

  if (!AddNodePoly(head, coef, expn)) {

  return ERROR;

  }

  } while (TRUE);

  return OK;

  }

  Status print(Poly head) {

  CHECK(head);

  Poly p = head->next;

  while (p) {

  printf("%1.1f", p->coef);

  if (p->expn)

  printf("*x^%d", p->expn);

  if (p->next && p->next->coef > 0)

  printf("+");

  p = p->next;

  }

  printf("\n");

  return OK;

  }

  Status AddPoly(Poly *a, Poly *b) {

  CHECK(*a&&*b&&*a!=*b);

  Poly p = *a,p1 = (*a)->next,p2 = (*b)->next,t;

  while (p1 && p2) {

   

首页 上一页 1 2 下一页 尾页 1/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇找距离最近油价最低的加油站 下一篇C语言连接mysql数据库

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: