lundi 11 novembre 2019

C++ If-statement variable scope

I have this function which when I run it it gives me the wrong answer due to the scope of the variable numer. Is there a way to use only one return statement for this function. I had to separate return statement which gave me the right answer (you can see with the //).

double calc_real_root(double a, double b, double c, double disc, double operation)
{ 
  double denom=2*a;
  double numer;
  if (operation == ADD)
  {
    double numer = -b + sqrt(disc);
    //return numer / denom ;
  }

  else 
  {
    double numer = -b - sqrt(disc);
    //return numer / denom ;
  }
  return numer / denom ;
}

Aucun commentaire:

Enregistrer un commentaire