我正在尝试编写一个算法来找到 f(x) = x^4 -4x +1 的根我应该得到这个函数的 4 个根 2 个实数和虚数。我用c写了这个算法。但是,如果它写得很好以及我应该为 a 和 b 输入什么样的初始猜测,请不要这样做,因为每次我运行程序它都会给我不同的数字这是我的代码,感谢您的帮助:
#include<stdio.h>
#include<math.h>
int computeroots(double, double, double, double);
int main()
{
double a ,b, soln;
double epsilon = pow(10, -8);
int MaxIter;
printf("please enter an initial guess for a: \n");
scanf("%ld",&a);
printf("please enter a second guess for b: \n");
scanf("%ld", &b);
printf("please enter the maximum number of iteration: \n");
scanf("%d", &MaxIter);
soln = computeroots(a, b, epsilon, MaxIter);
printf("Here is the solution: %d \n", soln);
return 0;
}
int computeroots(double a, double b, double epsilon, double MaxIter)
{
float FA = pow(a,4) - 4*a + 1;
float FB = pow(b,4) - 4*b +1;
float FP;
int i =1;
float p;
if(FA * FB < 0)
{
while(i<MaxIter)
{
p = a + (b-a)/2;
FP = pow(p,4) - 4*p +1;
if(FP == 0 || (b-a)/2 < epsilon)
{
return p;
break;
}
i++;
if(FA*FP > 0)
{
a = p;
FA = FP;
}
else
{
b = p;
}
}
}
}