链表实现二分法求根

#include<iostream>
#include<iomanip>
#include<cmath>
using namespace std;
class poly{
public:
double c;
int e;
poly*next;
};
poly*input();
double f(poly*head,double x);
double root(poly*head,double a, double b);
int main(){
poly*head;
double a, b;
head = input();
cin >> a >> b;
cout << setiosflags(ios::fixed) << setprecision(3);
cout << root(head, a, b) << endl;
return 0;
}
poly*input(){
/*输入多项式的各项,返回头指针*/
poly*p = new poly;
poly*head = p, *p1 = p;
while (cin >> p->c >> p->e){
p1 = p;
char ch = getchar();
p = new poly;
p1->next=p;
if (ch == ' ') /*遇到空格跳出输入*/
break;
}
delete p;
p1->next = NULL;
return head;
}
double f(poly*head, double x){
/*任意一个数x,得到表达式的值*/
double sum = 0.0;
while (head){
sum += head->c*pow(x, head->e);
head = head->next;
}
return sum;
}
double root(poly*head, double a, double b){
/*二分法求根*/
double x;
while (b-a>0.001){
x = (a + b) / 2;
if (abs(f(head,x)) < 0.001)
return x;
else if (f(head,a)*f(head,x) < 0)
b = x;
else
a = x;
}
return a;
}

原文地址:https://www.cnblogs.com/td15980891505/p/4433058.html