-6

guys, I am trying to make a code that can factor quadratic equation but this only works when the equation is positive. Here is the code. Please help

#include<iostream>
#include<conio.h>
#include<stdio.h>
using namespace std;

int main()
{
    double a,b,c,ac,n,m;
    cout<<"Enter a: ";cin>>a;cout<<endl;
    cout<<"Enter b: ";cin>>b;cout<<endl;
    cout<<"Enter c: ";cin>>c;cout<<endl;
    ac = a*c;
    for(n=0;n<=ac;n=n+2)
    {
     m= ac/n;

   if(n+m==b&&n*m==c)
    {
       cout<<"(x + "<<n<<") (x + "<<m<<")"<<endl;
       break;
    }

   }
    return 0;
}
  • 3
    Umm..why don't you simply find out the roots using the [formula](https://wikimedia.org/api/rest_v1/media/math/render/svg/3c235086de4df3b8cfbbb622d91a791a91fe752b)?? – Aditi Rawat Feb 25 '18 at 16:37
  • 1
    Consider what happens in `n<=ac` when `ac` is negative. When comparing `double`s for equality you should also read this [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Bo Persson Feb 25 '18 at 17:52

1 Answers1

1

Building on what @Aditi Rawat said, I've wrote a little program that does what you need using the quadratic roots formula. Not sure if you need to do it that way or not but this solves the problem:

#include <iostream>
#include <cmath>
using namespace std;

int main()
{
    double a, b, c;
    cout<<"Enter a: "; cin>>a; cout<<endl;
    cout<<"Enter b: "; cin>>b; cout<<endl;
    cout<<"Enter c: "; cin>>c; cout<<endl;

    double x_positive, x_negative;
    if((pow(b,2) - 4*a*c) >= 0) {
      x_positive = (-b + sqrt(pow(b,2) - 4*a*c)) / 2*a;
      x_negative = (-b - sqrt(pow(b,2) - 4*a*c)) / 2*a;
      cout << "Root 1: " << x_positive << endl;
      cout << "Root 2: " << x_negative << endl;
    } else cout << "Roots are complex" << endl;

    return 0;
}
Daniel Marques
  • 506
  • 5
  • 20