M.K M.K - 9 months ago 36
C++ Question

Mantain the original value in a recursive function c++

I am trying to solve a square root in a recursive way. I do not want the code to solve that! I am almost done, but I do not know how to mantain the original value of the function:

float raizCuadrada(float num, float err) {

float nuevo = num / 2;
float resta=(nuevo*nuevo)-num;


if(resta>err){
return (raizCuadrada(nuevo, err));
}
else if (resta <= err) {
return (nuevo);
}
}


I basicly want to know how to "save" that first "num" call, somewhere, to use it ALWAYS in the "resta", the "- num" should be always the number that 1st put.

NOTES: I cannot input more inputs. I can only input 1 number and the error.

Answer Source

You can define a global variable at the top of your code.

float num_fixed;

float raizCuadrada(float num, float err) {

    float nuevo = num / 2;
    float resta=(nuevo*nuevo)-num_fixed;

    if(resta>err){
        return (raizCuadrada(nuevo, err));
    }
    else {
        return (nuevo);
    }   
}

int main(void){
  float num = 2.0;
  float err = 0.000001;
  float output;
  num_fixed = num;
  output = raizCuadrada(num, err);
}