该程序找到代码中定义的函数 f 的第一个根。这个函数有 5 个根。(x=1,2,3,4,5) 我希望找到该程序中的所有根并将它们打印到屏幕上。在 main 函数中,您可以看到我试图编写一个 while 循环来执行此操作(在下面的代码中注释掉)。但这不起作用,它只是将相同的结果无限地打印到屏幕上。任何帮助,将不胜感激。
// This program finds the roots of a polynomial using the half interval search method
#include <iostream> //preprocessor directive needed in order to use std::cout
//and std::cin
#include <iomanip> //preprocessor directive needed in order to use
//a manipulator which uses an argument
using namespace std; //avoids having to uses std:: with cout and cin
//declare the variables
const double a = 0.0, b = 6.0; //limits for f()
double px = 1e-6; //define the precision
double x = a, dx = 1.0; //start value and initial interval
double root;
//prototypes for f()
double f (double x);
double halfIntervalSearch (double a, double b, double dx, double px);
int main (int argc, char* argv[])
{
//Inform the user what the program does
cout << "This program finds the roots of\n"
"f(x) = x^5 - 15x^4 + 85x^3 - 225x^2 + 274x -120 = 0\n"
"which is bracketed by [" << a << ", " << b <<
"] using the half interval search method." << endl;
cout << "Searching...\n"; //Lets user know what is happening
root = halfIntervalSearch(a,b,dx,px); //pass the variable
//print out results
//while (x <= b)
{
//x = root + 2*px; //reset value of x
cout << "\nRoot at x = " << setw(10) << setprecision(7) << fixed
<< root << " of value " << f(root) << endl;
}
//allow user to see the results before ending the program
cout << "\n\nPress Enter to end the program";
cin.get();
}
////////////////////////////////////////////////////////////////////////////////
//define f()
double f (double x)
{
return (x*x*x*x*x)-(15*x*x*x*x)+(85*x*x*x)-(225*x*x)+(274*x)-120;
}
///////////////////////////////////////////////////////////////////////////////
//define halfIntervalSearch()
double halfIntervalSearch (double a, double b, double dx, double px)
{
while ((x <= b) && (dx > px))
{
while ( f(x)* f(x+dx) > 0) //while there are no roots
{
//keep track while program finds roots
cout << "x = " << setw(18) << x << " | dx = " << setw(15)
<< right << dx << endl;
x += dx; //step forward
}
dx = dx/2; //half the interval
}
return x;
}