使用C語言的鏈結結構儲存二個多項式,以建立副程式執行多項式相

2009-05-08 7:51 pm
使用C語言的鏈結結構儲存二個多項式,以建立副程式執行多項式相加
A(X)+B(X)=C(X)
A(X)= 7x^5 +3x^2+8
B(X)= 5x^6+2x^5+9X^2+x+12
C(X) = 5X^6+9X^5+12X^2+X+20

回答 (2)

2009-05-10 4:02 am
✔ 最佳答案
除意見001外, 這裡提供一個用不定參數來設定多項式的程式供參考.
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>

typedef struct stMulti
{
struct stMulti * Next;
int Len;
int Num[1];
}Multi;
Multi * First = NULL;
Multi * Last = NULL;

// 產生新多項式
Multi * NewMulti(int n)
{
Multi * m = (Multi *) malloc(sizeof(Multi)+sizeof(int)*n);
m->Next = NULL;
m->Len = n;
while(--n>=0) m->Num[n] = 0;
if (First==NULL) First = m;
if (Last!=NULL) Last->Next = m;
return Last = m;
}
// 建立多項式 : exp為最高冪值, 後為int型態係數
Multi * CreateMulti(int exp, ... )
{
int n = (exp<0)? 1: exp+1;
Multi * m = NewMulti(n);
va_list arg;
va_start( arg, exp);
while(--n>=0) m->Num[n]=va_arg(arg, int);
va_end( arg);
return m;
}
// 多項式相加 A+B
Multi * MultiAdd(Multi *A, Multi *B)
{
int n = (A->Len>B->Len)? A->Len: B->Len;
Multi * m = NewMulti(n);
while(--n>=0)
m->Num[n]= (n<A->Len? A->Num[n]: 0) + (n<B->Len? B->Num[n]: 0);
return m;
}
// 顯示多項式
void PrintMulti(char *s, char c, Multi *A)
{
char f1[][10] = { "+%d", "%d", "+%d%c", "%d%c", "+%d%c^%d", "%d%c^%d" };
char f2[][8] = { "+%c", "%c", "+%c^%d", "%c^%d" };
int m, o=0;
int n = A->Len;
printf(s);
while(--n>=0)
{
if (A->Num[n]==0) continue;
m = n>1? 4: n*2;
if (A->Num[n]<0 || o++==0) m++;
if (n!=0 && A->Num[n]==1) printf( f2[m-2], c, n);
else printf( f1[m], A->Num[n], c, n);
}
printf("\n");
}
// 清除配置體
void ClearAll()
{
Multi * node = First;
Multi * f;
for( ;(f=node)!=NULL; free(f)) node=node->Next;
First = Last = NULL;
}
// 主程式
int main()
{
Multi *A, *B, *C;
//A(X)= 7x^5+3x^2+8 冪5 係數序: 7 0 0 3 0 +8
PrintMulti( "A(x) = ", 'x', A = CreateMulti( 5, 7, 0, 0, 3, 0, 8 ) );
//B(X)= 5x^6+2x^5+9X^2+x+12 冪6 係數序: 5 2 0 0 9 1 +12
PrintMulti( "B(x) = ", 'x', B = CreateMulti( 6, 5, 2, 0, 0, 9, 1, 12 ) );
//C(X) = A(X)+B(X) = 5X^6+9X^5+12X^2+X+20
PrintMulti( "C(x) = A(x)+B(x) = ", 'x', C = MultiAdd( A, B ) );
ClearAll();
system("pause");
return 0;
}



2009-05-09 20:04:15 補充:
執行結果 :

A(x) = 7x^5+3x^2+8
B(x) = 5x^6+2x^5+9x^2+x+12
C(x) = A(x)+B(x) = 5x^6+9x^5+12x^2+x+20

2009-05-09 20:11:33 補充:
程式部分因受限字數限制而有所縮編... 如 :
PrintMulti( "A(x) = ", 'x', A = CreateMulti( 5, 7, 0, 0, 3, 0, 8 ) );

原可為 :
Multi *A= CreateMulti( 5, 7, 0, 0, 3, 0, 8 );
PrintMulti( "A(x) = ", 'x', A );
2009-05-09 3:44 pm


收錄日期: 2021-04-30 12:58:47
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20090508000010KK03066

檢視 Wayback Machine 備份