-1

I'm trying to write a program that calculates the root of f(x) = x^2 -2, but it does not seem to change the values of x, fa, and fb.

  int x2(float a, float b)
    {
        float tmp = (a + b) / 2; 
        return tmp; 
    }
    
    int func(float a)
    {
        float tmp = (a * a) - 2;
        return tmp;
    } 
    
    int main()
    {
        float a = 1, b = 2;
        float fa = func(a), fb = func(b);
        float y = 0, x=0; 
    
        while (fa < 0 && fb > 0)
        {
    
            y = x2(a,b);
            x = func(y);
    
            if (x < 0) { a = x2(a, b); b = b; }
            if (x > 0) { a = a; b = x2(a, b); }
            if (x == 0) { cout << "Zero-Point: " << x << endl; break; }
    
            fa = func(a), fb = func(b);
        }
    }
Zeta
  • 103,620
  • 13
  • 194
  • 236
  • 2
    This program is small enough that you can step through it in a debugger and compare the results against a hand-calculation. I think you'll find interesting things when you step through the calls to `x2` and `func`. (Also, your variable names are confusing. You use the variable named `x` to represent the y-coordinate, and the variable named `y` to represent the x-coordinate.) – Raymond Chen May 28 '22 at 13:41

1 Answers1

1

All your functions return int, but func and x2 should return float. Otherwise you will end up with x2 returning 1 on x2(1, 2) and thus a = y = 1 permanently.

Zeta
  • 103,620
  • 13
  • 194
  • 236