Hello everyone. I'm new to C++ and need help passing a function pointer to handle error states. temp1 is cin input from user and temp2 is user guess for square root.
Here is the code so far:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
double squareroot(double temp1, double temp2, double (*fn)(double))
{
if (temp1 < 0)
return fn(temp1); // if negative number, pass to error handler to convert to positive number
double prev = temp2;
temp2 = (0.5) * (temp2 + ( temp1 / temp2 ));
if (prev - temp2 < 0.0000001 )
return(temp2);
elsereturn squareroot(temp1,temp2,errorHandle1);
}
Right now I'm not able to pass to get the right return from my errorHandle1 function, which essentially converts a negative number to positive. The program is never getting to that point though.
I can provide additional code for my program if necessary. Thanks in advance for any help and the time.
The program is never getting to that point though.
Could you explain which point it is not getting to? Maybe you meant to assign fn(tem1) to temp1, or have fn() modify it via a reference?
Also, the "C++ way" to do this is usually with Exceptions. I'm surprised that being to new C++ you already understand function pointers but not exceptions! Are you looking at C++ from another langauge? Just curious ;)
Hey LB. Thanks for the response. My introductory C++ teacher was not very good, so there are a few things that are missing for sure I'm coming more from a web design background, so programming is a bit new to me.
In regards to my question, the temp1 argument doesn't seem to be getting passed to the errorHandle function. I think everything is setup right, but obviously its not (otherwise it would be running).
I'm not looking for anyone to rewrite the code, just try to grasp concept of function pointers a little better and get a few hints on how to fix this issue.
if (temp1 < 0)
return fn(temp1); // Couldn't get this function to pass properly, so i converted to positive the dirty way
// temp1 *= (-1); // dirty solution
If the 'dirty solution' is the result you want to happen, then you should know that your current code is return-ing from squareroot with the value returned by fn. As I said before you may want temp1 = fn(temp1) instead of exiting the entire squareroot function...
Nice, that seemed to have done the trick. I knew something wasn't getting passed properly. I didn't realize I was exiting the squareroot function at that point. I guess it was a basic oversight. I sincerely appreciate the time and help LB.