码迷,mamicode.com
首页 > 其他好文 > 详细

链表实现二分法求根

时间:2015-04-16 21:32:02      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:

#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 == ‘\n‘) /*遇到空格跳出输入*/
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;
}

链表实现二分法求根

标签:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!