0
In this code if I dont define "f" in the if else stat then the output comes out wrong. Why is it imp to define it in the stats??
cout<<"Coeff for x^2 = "; float a,b,c; cin>>a; cout<<"Coeff for x = "; cin>>b; cout<<"Constant = "; cin>>c; float d; float e=pow(b,2); float f=sqrt(d); if((e-4*a*c)>=0) { d=(e-(4*a*c)); f=sqrt(d); cout<<"Roots are = \n"; cout<<"\t\t"<<(-b+f)/(2*a)<<endl; cout<<"\t\t"<<(-b-f)/(2*a)<<endl; } else if(e-(4*a*c)<0) { d=((4*a*c)-e); f=sqrt(d); cout<<"Roots are = \n"; cout<<"\t\t"<<(-b/(2*a))<<"+"<<f/(2*a)<<"i"<<endl; cout<<"\t\t"<<(-b/(2*a))<<"-"<<f/(2*a)<<"i"<<endl;
2 Antworten
+ 2
Because you need to calculate d first, and because the value of f depends on whether you are in the if case or the else one.
#include <iostream>
#include <cmath>
using namespace std;
int main() {
float a, b, c, d, f;
cout << "Solving ax^2 + bx + c = 0" << endl;
cout << "Enter a: ";
cin>>a;
cout << a << endl;
cout << "Enter b: ";
cin >> b;
cout << b << endl;
cout << "Enter c: ";
cin >> c;
cout << c << endl;
d = b*b - 4*a*c;
cout << "Roots are: " << endl;
if(d >= 0) {
f=sqrt(d);
cout << "\t\t" << (-b+f)/(2*a) << endl;
cout << "\t\t" << (-b-f)/(2*a) << endl;
} else {
f=sqrt(-d);
cout << "\t\t" << (-b/(2*a)) << " + " << f/(2*a) << "i" << endl;
cout << "\t\t" << (-b/(2*a)) << " - " << f/(2*a) << "i" << endl;
}
return 0;
}
0
Thank you for the answer. I knew it could be made simpler. sqrt(-d), that's what I was missing. Thanks again.