Skip to content

Instantly share code, notes, and snippets.

@juanfal
Created October 16, 2012 11:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juanfal/3898804 to your computer and use it in GitHub Desktop.
Save juanfal/3898804 to your computer and use it in GitHub Desktop.
ecuación de segundo grado con función
// ecu2gradofun.cpp
// juanfc 2009-11-07
//
#include <iostream>
#include <cmath>
using namespace std;
enum TIPOEC {CUALX, ABSURDA, PRIMERG, DOBLE, IMAG, DOSSOLS};
TIPOEC ecu2grado(const float a, const float b, const float c,
float& x1, float& x2)
{
TIPOEC tipo;
if (a == 0.0 and b == 0.0 and c == 0.0) {
tipo = CUALX;
} else {
if (a == 0.0) { // no es una ec. de seg. grado
if (b == 0.0) { // a=0, b=0 y c != 0
tipo = ABSURDA;
} else {
tipo = PRIMERG;
x1 = -c/b;
}
} else {
float discr = b * b - 4.0 * a * c;
if (discr == 0.0) {
tipo = DOBLE;
x2 = x1 = -b/(a*2);
} else {
if (discr < 0.0) {
x1 = -b/(2*a);
x2 = sqrt(-discr)/(2*a);
tipo = IMAG;
} else {
float d = sqrt(discr);
tipo = DOSSOLS;
x1 = (-b+d)/(2*a);
x2 = (-b-d)/(2*a);
}
}
}
}
return tipo;
}
int main(int argc, char *argv[])
{
float a, b, c, x1, x2;
cout << "Resolvedor de ecuaciones del tipo ax2 + bx + c = 0" << endl;
cout << "Introduce a b c: ";
cin >> a >> b >> c;
switch (ecu2grado(a, b, c, x1, x2)) {
case CUALX:
cout << "Válida para cualquier x" << endl;
break;
case ABSURDA:
cout << "Imposible para ningún x" << endl;
break;
case PRIMERG:
cout << "Una sóla solución x: " << x1 << endl;
break;
case DOBLE:
cout << "Una solución doble x1=x2= " << x1 << endl;
break;
case IMAG:
cout << "Solución compleja conjugada: "
<< x1 << " +- i " << x2 << endl;
break;
case DOSSOLS:
cout << "Dos soluciones diferentes:" << endl;
cout << "x1: " << x1 << endl;
cout << "x2: " << x2 << endl;
break;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment