+ 1

[SOLVED] What's wrong with my code? program created to solve many sets of quadratic equations

#include <iostream> #include <cmath> using namespace std; int a, b, c, d; double x1, x2; int main() { cout << "Input for a: "; cin >> a; cout <<"Input for b: "; cin >> b; cout << "Input for c: "; cin >> c; cout << "\n"; if (a = 0){ cout <<"Not Quadratic\n"; if (b = 0){ cout << "a = 0\nb = 0\nBye"; } else{ x1 = (-c/b); cout << "x1 = "<< x1; } } else{ d = (b^2-(4*a*c)); if(d<0){ cout << "No Real Answer. Fail to take the square root of Negative Value.\n"; } else{ x1 = (-b+sqrt(d))/(2*a); x2 = (-b-sqrt(d))/(2*a); cout << "Root 1: x1 = "<<x1<<endl; cout << "Root 2: x2 = "<<x2<<endl; } } return 0; }

20th Jan 2022, 2:26 AM
Jevon Harry
Jevon Harry - avatar
3 Réponses
+ 5
The "^" is a bitwise XOR operator, not exponent. Use "pow ()" function from cmath to find the power of the number instead.
20th Jan 2022, 2:46 AM
Arsenic
Arsenic - avatar
+ 3
I found 3 bugs. #include <iostream> #include <cmath> using namespace std; int a, b, c, d; double x1, x2; int main() { cout << "Input for a: "; cin >> a; cout <<"Input for b: "; cin >> b; cout << "Input for c: "; cin >> c; cout << "\n"; if (a == 0){ //Debug 1 cout <<"Not Quadratic\n"; if (b == 0){ //debug 2 cout << "a = 0\nb = 0\nBye"; } else{ x1 = (-c/b); cout << "x1 = "<< x1; } } else{ d = (b*b-(4*a*c)); //debug 3 if(d<0){ cout << "No Real Answer. Fail to take the square root of Negative Value.\n"; } else{ x1 = (-b+sqrt(d))/(2*a); x2 = (-b-sqrt(d))/(2*a); cout << "Root 1: x1 = "<<x1<<endl; cout << "Root 2: x2 = "<<x2<<endl; } } return 0; }
20th Jan 2022, 3:00 AM
Solo
Solo - avatar
+ 1
Thank You Everyone!
20th Jan 2022, 4:57 AM
Jevon Harry
Jevon Harry - avatar