Recursion function problem not returning correct answer

To give you a brief summary of the code it is basically trying to find the root of a function between two points using bisection.

My code works perfectly, but for some reason, it is not returning the variable "m" in the if statement "else if (b-a<precision)" but rather just returning the base case of 0. It doesn't make any sense to me because the if statement stops the recursive call and when I put a "cout << m;" under the if statement it prints out the correct value, but it just won't return it.

 ``12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061`` ``````//Nick Barry //Homework 9 //12/2/19 //This code will find the root of a function between two points #include #include using namespace std; double bisect(double f(double x), double a, double b, double precision); // POST: return approximate root of f between a and b double f(double x); // POST: function to be passed to bisect: x^3 - 2x - 3 int main() { double root; // root of f() between a and b cout.setf(ios::fixed | ios::showpoint); // set up output for fixed point with 10 decimals cout.precision(15); cout << "Bisection by Nick Barry\n\n"; cout << "Trace of calls\n"; cout << setw(20) << "a" << setw(20) << "m" << setw(20) << "b" << endl; root = bisect(f, 1.0, 2.0, 1.0e-15); // find root of f between 1.0 and 2.0 with tolerance 10^-15 cout << "\nThe root of x^3 - 2x - 3 between 1 and 2 is approximately " << root << endl << endl; return 0; } double bisect(double f(double x), double a, double b, double precision) // POST: return approximate root of f between a and b { double m; m=(a+b)/2;//finds the midpoint of two values and sets it to m cout << setw(20) << a << setw(20) << m << setw(20) << b << endl; if (m==0) return m;//if midpoint is zero then root has been found else if (b-a
Last edited on
On lines 49 and 51 it should be
`... return bisect ....`
not just
`... bisect ...`

Unrelated, but it should also be
`f(m)==0`
not
`m==0`
on line 43
Last edited on
Oh duh, thank you!