这是使用二分法求解多项式方程的程序 [英] This is the program to solve polynomial equations using bisection method
本文介绍了这是使用二分法求解多项式方程的程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
void bisect(float *p,int n,int a);
float value(float *p,int n,int a);
int main()
{
int a,i;
float *p;
printf("enter the degree of the polynomial\n");
scanf("%d",&a);
p=(float *) malloc(a*sizeof(float));
for(i=0;i<=a;i++)
{
printf("enter the coefficient of x^%d\n",i);
scanf("%f",p+i);
}
for(i=-100;i<100;i++)
{
if(value(p,i,a)*value(p,i+1,a)<0)
{
bisect(p,i,a);
}
}
return 0;
}
float value(float *p,int n,int a)
{
float sum=0;
int i;
for(i=0;i<=a;i++)
{
sum=sum+*(p+i)*pow(n,i);
}
return sum;
}
void bisect(float *p,int n,int a)
{
float j,k,l;
int i;
j=n;k=n+1;l=(j+k)/2;
for(i=0;i<50;i++)
{
if(value(p,j,a)*value(p,l,a)<0)
{
j=j;k=l;l=(j+k)/2;
}
else if(value(p,l,a)*value(p,k,a)<0)
{
l=(l+k)/2;j=l;
}
}
printf("the root of the equation is %f\n",l);
}
这是通过使用二分法完成的,我知道代码没有优化,我无法从我的算法中导出任何根,我想找出任何逻辑错误,因为我经过多次调查后都找不到。我想知道数据类型的等同是否有任何错误。提前谢谢。
This is done by using bisection method, and i know that the code isn't optimized , i am unable to derive any root from my algorithm though, i want to find out any logical errors as i could find none after much investigation. I would like to know if there is any fault with the equating of data types. thanks in advance.
推荐答案
如果您希望其他人查看您的代码,您必须使用合理的变量名称。请看一下: http://www2.lv.psu.edu/ ojj / courses / cmpsc-201 / numerical / bisection.html [ ^ ]
我不会给你代码,因为这是作业但是:
1.解决此问题:
If you want other people to look at your code you must use sensible variable names. Have a look at this: http://www2.lv.psu.edu/ojj/courses/cmpsc-201/numerical/bisection.html[^]
I won't give you code because this is homework but:
1. Fix this:
p=(float *) malloc(a*sizeof(float));
for(i=0;i<=a;i++)
2.严重 - 将声明更改为:
2. Critical - Change declaration to:
double value(float *p, double x, int a);
并修复实施。
3.另外:
and fix implementation.
3. Also:
double j,k,l;
4.主要内容
4. In main
#include <iostream>
using namespace std;
和
and
cin.ignore();
cin.get();
return 0;
使用link中的值作为测试。
Use values from link as your test.
这篇关于这是使用二分法求解多项式方程的程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文