Skip to content

Instantly share code, notes, and snippets.

@juanfal
Created October 16, 2012 23:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juanfal/3902653 to your computer and use it in GitHub Desktop.
Save juanfal/3902653 to your computer and use it in GitHub Desktop.
Solución de la ecuación de segundo grado mediante if-elseifs planos, no anidados unos dentro de otros. Parece más fácil que anidando, ¿no? ¿Puedes poner esta solución dentro de una función?
// ec2gradoPlana.cpp
// juanfc 2010-10-20
//
// Resuelve ecuaciones del tipo ax2 + bx + c=0
#include <iostream>
#include <cmath>
using namespace std;
int main() {
float a, b, c;
cout << "Resolvedor de ecuaciones del tipo ax2 + bx + c = 0" << endl;
cout << "Introduce a b c: ";
cin >> a >> b >> c;
float discr = b * b - 4.0 * a * c;
if (a == 0.0 and b == 0.0 and c == 0.0) {
cout << "Ecuación válida para cualquier x" << endl;
} else if (a == 0.0 and b == 0.0) { // a=0, b=0 y c != 0
cout << "Ecuación absurda" << endl;
} else if (a == 0.0 and b != 0.0) {
cout << "Solución única x = " << -c/b << endl;
} else if (discr == 0.0) { // a != 0, es una ecuación de segundo grado
cout << "Solución doble x = " << -b/(a*2) << endl;
} else if (discr < 0.0) {
float re, im;
re = -b/(2*a);
im = sqrt(-discr)/(2*a);
cout << "Solución imaginaria x = " << re;
cout << " +/- " << im << " j" << endl;
} else {
float d = sqrt(discr);
cout << "Dos soluciones reales:" << endl;
cout << "\tx1 = " << (-b+d)/(2*a) << endl;
cout << "\tx2 = " << (-b-d)/(2*a) << endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment