Please tell me what do you think of the written code below, is it easy to follow? Does the code tells you what it does, or you have struggled realizing whats going on? and so on. Feel free to give suggestions, tips, advices and criticize! This will help me and help other members too...
Note:i'm trying to know how other developers see my code & trying to see where i go wrong. Thus, the best way to evaluate myself is to post my source code and see what do you think about it.
bool quadraticFormula(double a, double b, double c, double *totalResults)
{
double D = sqrt( (b*b) - (4*a*c) );//shorter name
if (!a)// a==0 => 2*a==0
{
cout<<"Denominator is zero\n";
returnfalse; // function failed -you can also use exceptions-
}
totalResults[0] = ( -b + D)/(2*a);
totalResults[1] = ( -b - D)/(2*a);
returntrue;//function succeded
}
int main(void)
{
double a, b, c;
double x[2];
cout<<"Please Enter a, b, and c to get Results of x:\n";
cout<<"a: ";
cin>>a;
cout<<"b: ";
cin>>b;
cout<<"c: ";
cin>>c;
if ( quadraticFormula(a, b ,c, x) )
{
cout<<"\nYour Results are:"<<endl;
cout << x[0] << endl << x[1] << endl; //you don't really need a loop here
}
system("pause");//better not using this, see http://www.cplusplus.com/forum/articles/7312/return 0;
}
From a usability standpoint, it is possible for there to be zero, one, or two solutions. The function as written does not allow the user to know how many solutions there are. Moreover, in the case of zero solutions, the function likely tries to take the square root of a negative number which will probably crash (can't try it at the moment).
Also, IMNSHO (though others will differ), I'd rather see the function take two reference parameters instead of a pointer because pointers are prone to programming error (pointer to unallocated memory, memory block that is too small, NULL pointer, etc), whereas references are much easier to get right. Another approach could be to return a struct containing the roots and the number of valid roots.
From a technical standpoint, the method you are using to compute the roots is prone to signifcant error if b^2 ~= 4ac due to catastrophic cancellation (research What Every Computer Scientist Should Know About Floating Point Arithmetic). [Catastrophic cancellation essentially means that the result will be accurate to zero decimal places.]