+ 1
Why this code not working properly for value pairs like 5 , 1 and 3
https://code.sololearn.com/cTnsKpM5Mhwf/?ref=app Here in this code when I give a value which tend to solve for imaginary roots it donot work completely perfect . Always value of variable root1real and rootreal2 is zero.
4 Answers
+ 1
#include <iostream>
#include<cmath>
using namespace std;
int main() {
cout<<"Enter Coffecient Of x^2 :";
int a;
cin>>a;
if (a == 0) {
cout<<"Coffecient of x^2 can't zero";
}
else {
cout<<"\nEnter Coffecient Of x :";
int b;
cin>>b;
cout<<"\nEnter Constant Term :";
int c;
cin>>c;
int d = (b * b) - (4 * a * c);
if (d >= 0) {
double root1 = ((- b) + sqrt(d))/(2.0 * a);
double root2 = ((- b) - sqrt(d))/(2.0 * a);
cout<<"\nRoot1 = "<<root1;
cout<<"\nRoot2 = "<<root2;
}
else {
d *= -1;
double root1real = (- b)/(2.0 * a);
double root2real = (- b)/(2.0 * a);
double root1img = (sqrt(d))/(2.0 * a);
double root2img = (sqrt(d))/(2.0 * a);
cout<<"\nRoot1 = "<<root1real<< " + "<<root1img<<"i";
cout<<"\nRoot2 = "<<root2real<<" - "<<root2img<<"i";
}
}
}
+ 2
In your code: (- b)/(2 * a)
b was integer
a was integer
when you multiply/divide etc an integer by another integer you get integer(that is 2*a = integer)
But to get a correct answer, we need our denominator to be of decimal type and therefore by making 2 or 'a' a double or float type solved the problem.
(- b)/(2.0 * a)
or
(- b)/(2 * a*1.0) would work.
Because integer/double equals to double.
+ 2
Rohit thank you now I got it
+ 1
Rohit thankyou very much . But can you Explain me how by making 2 to 2.0 corrected the problem