如何解决计算给定值的多基因组
我想为一个给定值评估一个多项式,因此我使用了一个链表来存储系数和指数,并且我定义了一个函数evaluate()
来为给定值评估该多项式。在输出时确实有问题,它总是显示值0.00000
我可以得到一些帮助吗?预先感谢。
这是完整的代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct list
{
int coef;
int expo;
struct list* next;
}list;
int compare(char* s1,char* s2)
{
int i=0;
char c1,c2;
do
{
c1= (*(s1+i));
c2= (*(s2+i));
i++;
if(c2 == '\0' || c1 == '\0')
return c1-c2;
}while(c1==c2);
return c1-c2;
}
int transform(char* arr)
{
int i,sign=0;
int s=0;
if((*arr) == '-') sign=1;
for(i=0;arr[i]!='\0';i++)
{
if(arr[i]>=0 && arr[i]<=9)
s=s*10+(arr[i]-'0');
}
if(sign) return -s;
return s;
}
list* insert(list* head,char* coef,int expo)
{
list* node=(list*)malloc(sizeof(list));
if(node==NULL)
{
printf("Stack Overflow");
exit(1);
}
node->next=NULL;
node->coef=transform(coef);
node->expo=expo;
if(head==NULL) return node;
list* temp=head;
while(temp && temp->next)
temp=temp->next;
temp->next=node;
return head;
}
float power_of(float x,int expo)
{
if(expo==0) return 1;
int i=1;
float s=1;
if(expo > 0)
while(i++ <= expo)
s*=x;
else if (expo < 0)
while(i++ <= -expo)
s*=1.0/x;
return s;
}
float evaluate(list* head,float x)
{
if(head==NULL) return 0;
float s=0.0;
while(head)
{
s+=(head->coef)*power_of(x,head->expo);
head=head->next;
}
return s;
}
int main()
{
list* head=NULL;
char coef[11];
int expo,i=1;
float x;
printf("insert the polynome <type end to stop>:\n");
do
{
printf("insert the coefficient %d> : ",i);
scanf("%s",coef);
if(compare(coef,"end"))
{
printf("insert the exposnant %d> : ",i++);
scanf("%d",&expo);
head=insert(head,coef,expo);
}
}while(compare(coef,"end"));
printf("insert a value to evaluate the polynome : ");
scanf("%f",&x);
float value=evaluate(head,x);
printf("output : %f ",value);
return 0;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。