【本节内容】if...else...的使用
【练习题】解一元二次方程
【代码】
#include<iostream> #include<cmath> using namespace std; int main() { double a, b, c; double delta; double x1, x2, x; cin >> a >> b >> c; if (a == 0) { if (b == 0) { cout <<"不构成方程"<< endl; } else { x = -c/b; cout << "一元一次方程的根为:x=" << x << endl; } } else { delta = b * b - 4.0 * a * c; if (delta >= 0) { delta = sqrt(delta); x1 = (-b + delta) / 2.0 / a; x2 = (-b - delta) / 2.0 / a; cout << "方程有实根,分别是:" << "x1=" << x1 << " x2=" << x2 << endl; } else { delta = sqrt(-delta); x1 = -b / 2.0 / a; x2 = delta / 2.0 / a; cout << "方程有复根,分别是:" << "x1=" << x1 << "+j" << x2 << " x2=" << x1 << "-j" << x2 << endl; } } return 0; }