#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#define OK 1
#define ERROR 0
typedef int Status
;
typedef struct {
int coef
;
int exp
;
}Ployn
;
typedef struct {
Ployn
* elem
;
int length
;
}SqPloy
;
Status
InitSqPloy(SqPloy
& L
) {
L
.elem
= (Ployn
*)malloc(100 * sizeof(Ployn
));
if (!L
.elem
)
return ERROR
;
L
.length
= 0;
return OK
;
}
Status
CreatSqPloy(SqPloy
& L
, int m
) {
Ployn
* p
= L
.elem
;
printf("逐项请输入稀疏多项式的系数和指数,英文逗号隔开\n");
for (int i
= 0; i
< m
; i
++) {
scanf_s("%d,%d", &(p
->coef
), &(p
->exp
));
p
++;
L
.length
++;
}
return OK
;
}
Status
ShowSqPloy(SqPloy
& L
) {
Ployn
* p
= L
.elem
;
printf("P(X) =");
for (int i
= 0; i
< L
.length
; i
++){
printf("%d x exp(%d) ",p
->coef
,p
->exp
);
p
++;
}
printf("\n");
return OK
;
}
int Calculate(SqPloy
& L
, int x0
) {
int a
;
int s
= 0;
Ployn
* p
= L
.elem
;
for (int i
= 0; i
< L
.length
; i
++){
a
= p
->coef
* int(pow(x0
, p
->exp
));
p
++;
s
+= a
;
}
return s
;
}
int main() {
SqPloy L
;
InitSqPloy(L
);
CreatSqPloy(L
, 3);
ShowSqPloy(L
);
printf("多项式的结果为:%d",Calculate(L
, 3));
}
运行结果:
Calculate函数中,循环体执行次数为顺序表长度,时间复杂度 O(n)=n。
转载请注明原文地址:https://blackberry.8miu.com/read-18197.html