In: Computer Science
Write a program to input the coefficients of a quadratic equation and solve roots for all cases (including complex roots). VBA.
x=(b ^2) - (4ac)
I have it for 2 complex and 2 real and repeated.
Is that all cases?
Module Root
Sub Main()
'variable declaration'
Dim a As Integer
Dim b As Integer
Dim c As Integer
Dim x1 As Double
Dim x2 As Double
Dim img As Double
Dim real As Double
Dim dis As Double
'variable initialization
Console.WriteLine("Enter the value of a, b, and c: ")
a = Convert.ToInt32(Console.ReadLine())
b = Convert.ToInt32(Console.ReadLine())
c = Convert.ToInt32(Console.ReadLine())
dis = b*b - 4 * a * c
'calculate solution
If dis>0 Then
x1 = (-b + Math.Sqrt(b*b - 4 * a * c)) / (2 * a)
x2 = (-b - Math.Sqrt(b*b - 4 * a * c)) / (2 * a)
'display the result
Console.WriteLine("There are two real roots and they are:")
Console.Write("x1 = ")
Console.WriteLine(x1)
Console.Write("x2 = ")
Console.Write(x2)
End If
If dis=0 Then
x1 = (-b + Math.Sqrt(b*b - 4 * a * c)) / (2 * a)
'display the result
Console.WriteLine("There is only one real root:")
Console.Write("x = ")
Console.WriteLine(x1)
End If
If dis<0 Then
img = Math.Sqrt(-dis) / (2 * a)
real = -b / (2 * a)
'display the result
Console.WriteLine("There are two complex roots and they
are:")
If img >= 0 Then
Console.Write("x1 = ")
Console.Write(real)
Console.Write("-")
Console.Write(img)
Console.WriteLine("i")
Console.Write("x2 = ")
Console.Write(real)
Console.Write("+")
Console.Write(img)
Console.Write("i")
End If
If img < 0 Then
Console.Write("x1 = ")
Console.Write(real)
Console.Write(img)
Console.WriteLine("i")
Console.Write("x2 = ")
Console.Write(real)
Console.Write("+")
Console.Write(-img)
Console.Write("i")
End If
End If
End Sub
End Module
The screenshot of the above source code is given below:
OUTPUT: