Good day. Only recently began to learn programming. I set myself a task, to create a program for calculating the solution of quadratic equations, a discriminant. The program seems to be working properly, but has encountered the following problem, when entering a = 0, b = 0, c = 0, it gives an error about closing the program. How to avoid it? I apologize in advance if not so designed the topic.

#include <iostream> #include <math.h> using namespace std; int main() { int a, b, c; double x1, x2, x12, D; cout << "Let's try to solve the equation of the form ax^2+bx+c=0" << endl; cout << " Pls enter a: "<< endl;; cin >> a; cout << "Pls enter b: "<< endl;; cin >> b; cout << "Pls enter c: "<< endl;; cin >> c; if ((a == 0) && (b == 0) && (c == 0)) { cout << " does not exist " << endl;} // a*x^2+b*x+c=0 D = (pow(b,2))-4*a*c; cout << "D= " << D; if (D > 0) { x1 = ((-b) + sqrt(D)) / (2 * a); cout << " x1= " << x1; x2 = ((-b) - sqrt(D)) / (2 * a); cout << " x2= " << x2; } else { if (D == 0) { x12 = -b / (2 * a); cout << " x12= " << x12; } else { if (D < 0) cout << " x1,2 does not exist "; } } return 0; } 
  • Where did the condition if ((a == 0) && (b == 0) && (c == 0)) come from? - Grundy
  • it was an attempt to avoid a program crash under the condition that the variables are zero. - artmini
  • x12 = -b / (2 * a); division by 0. I think a debugger would help here. By the way, it's enough to check that a! = 0. - pavel
  • and you know that this condition is fulfilled only when all variables are equal to 0 ? - Grundy
  • @pavel, there and in the remaining divisions 2*a - Grundy

1 answer 1

You divide by 0. This behavior is possible only if A == 0. It is enough to add something like:

 if(a == 0) { cout << " Error! 'A' cant be equal zero" << endl; return 0; } 
  • why then the line if ((a == 0) && (b == 0) && (c == 0)) { cout << " does not exist " << endl;} does not work? Could it be that he believes that 0 == 0 before it reaches x1 = ((-b) + sqrt(D)) / (2 * a); - artmini
  • 1) The condition is not correct. The program crashes only when A == 0 (B and C are not important). 2) You, when the condition is triggered ((a == 0) && (b == 0) && (c == 0)) , only a message is displayed on the screen. It is necessary to complete the execution of the program. This is where the string return 0; helps return 0; - Jester
  • Yes, thank you, figured out! - artmini
  • by the way, if all coefficients are zero, then the solution still exists. - int3 pm