C++ troubles

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <iostream>
#include <cmath>                // for abs function
using namespace std;

// ----------------------------------------------
// Function prototypes

double find_root(double (*f)(double ), double a, double b, double tolerance);

double f(double x);

// ---------------------------------------------
// Main

int main(int argc, char** argv)
  {double a, b, root;

// Have the user enter the endpoints of the initial interval.
  while (1)
    {cout << "Enter the endpoints of an interval containing a root: ";
     cin >> a >> b;
     if (f(a) * f(b) < 0.0)
        break;
     else
        cout << "No sign change on this interval.  Try again." << endl;
    }

// Find a root and output it.
   root = find_root(f, a, b, .0004);
   cout << "Root = " << root << endl;

   cout << "That's all, folks!" << endl;
   return 0;
  }

// ------------------------------------------
// Function f follows.

double f (double x)
  {

        return (x*x*x) - (3.0*x) +1;
  }
double find_root(double (*f)(double x), double a, double b, double tolerance)
{
        while(abs(a-b) > tolerance)
        {
        double  mid= (a+b)/2;
                if(f(a)>=0 &&  f(mid)<=0 || f(a)<=0 && f(mid)>=0 )
                        b=mid;
   
                else
                        a=mid;
               
        }
};
This code is supposed too find the root of a number but no matter what is typed in the code returns nan assuming the signs are different.
you don't ever return anything from find_root.
Topic archived. No new replies allowed.