Quadratic equation help

This is my code for outputting roots from a quadratic equation. I am supposed to have the imaginary roots output in the form of A+Bi and A-Bi. I am confused as to how to do this, can anyone help?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
  #include <cmath>
#include <iomanip>
#include <iostream>

using namespace std;

void quad(double&,double&,double&,double&,double&);

int main()
{
	double a;
	double b;
	double c;
	double x1;
	double x2;
	char choice = 'y';






	cout <<"This program will find the roots of a quadratic"<<endl<<endl;

	do{

	cout <<"Please input the values for the coefficients; a, b, c"" (y=ax^2+bx+c)"<<endl<<endl;
cin>>a>>b>>c;

if (a==0)
{ cout <<"If a is 0, then it is a line. Can't divide by 0"<<endl<<endl;
}
else
{
quad(a,b,c,x1,x2);
if((b * b - (4 * a * c)) < 0)
{
cout<<"the imaginary root(s): "<<setw(5)<<fixed<<setprecision(3)<<x1<<"\t"<<x2<<endl<<endl;

}
else  
{
cout<<"the real root(s): "<<setw(5)<<fixed<<setprecision(3)<<x1<<"\t"<<x2<<endl<<endl;

}

}


cout <<"Would you like to run this again? y or Y for yes, anything else for no"<<endl<<endl;
cin >>choice;	

	}while (choice =='y' || choice =='Y');

	system ("Pause");
	return 0;

}


void quad(double&a, double&b, double&c, double&x1, double&x2)
{
	

	x1 = (-b+sqrt((b*b)-4*a*c))/(2*a);
	x2 = (-b-sqrt((b*b)-4*a*c))/(2*a);




}
You simply need not take "sqrt" of negative number. Instead split this number into "-1" and some positive number:

1
2
3
y = -5;
x = sqrt(y); // not correct
printf("%f * i", sqrt(-y)); // this way 
ok, how would i begin to implement that into my code? in my cout statement?
I don't think you should try to do everything in a cout statement.

And you could use a few more variables.

Right now, you have the variables x1 and x2 for the roots. However, each of those roots is actually made up of two components: A and B. What you should have are variables for the real and imaginary components of x1 and x2, for example, x1Re, x1Im, x2Re, and x2Im, or something like that. If the roots are real, the imaginary components will be 0.

Normally, a variable for the discriminant is also declared.
Then you calculate the value of the discriminant and decide what to do next depending on whether it is less than 0.

For example;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
double discrim;

discrim = b*b - 4*a*c;

if (discrim < 0){  // complex roots
//Remember to negate the sign of discrim before taking its square root
x1Re =               // calculate components of roots
x1Im = 
x2Re =
x2Im = 
}
else {                // real roots
x1Re =               // calculate components of roots
x1Im = 0.0;
x2Re =
x2Im = 0.0;
}

// Output the results. 


Topic archived. No new replies allowed.