Hacker News new | ask | show | jobs
by YogSothoth 5203 days ago
I'm with you alex, I tend to only use classes when I've got to maintain state, I just use a function otherwise. Here's how I'd likely code this ...

  #include <iostream>
  #include <string>
  #include <cmath>
  
  using std::string;
  using std::cout;
  using std::endl;
  
  static bool findRoots(
     double a,
     double b,
     double c,
     double &rootOne,
     double &rootTwo,
     string &errMsg
  )
  {
     if(a == 0.0)
     {
        errMsg = "Parameter 'a' cannot be zero";
        return(false);
     }
  
     double discriminant = b * b - 4 * a * c;
  
     if(discriminant < 0.0)
     {
        errMsg = "Discriminant cannot be less than zero";
        return(false);
     }
  
     double dSqrt = sqrt(discriminant);
     double twoA  = 2 * a;
  
     rootOne = (-b + dSqrt) / twoA;
     rootTwo = (-b - dSqrt) / twoA;
  
     return(true);
  }
  
  int main()
  {
     double a[] = { 0.0, 2.0, 2.0 };
     double b[] = { 1.0, 3.0, 1.0 };
     double c[] = { 2.0, 2.0, 0.0 };
  
     double rootOne;
     double rootTwo;
     string errMsg;
  
     for(int n = sizeof(a) / sizeof(a[0]), i = 0; i < n; i ++)
     {
        cout << "a: " << a[i] << ", b: " << b[i] << ", c: " << c[i] << endl;
  
        if(findRoots(a[i], b[i], c[i], rootOne, rootTwo, errMsg))
        {
           cout << rootOne << " " << rootTwo << endl;
        }
        else
        {
           cout << errMsg << endl;
        }
  
        cout << endl;
     }
  
     return(0);
  }
1 comments

thank you for your answer, but next time better use something like http://gist.github.com