A quadratic equation is a second-degree polynomial that has the form "ax^2 + bx + c = 0." The "a," "b" and "c" are the constants and "x" is the variable. When you solve a quadratic equation, you must have the values of the constants and solve for x, which always yields two values, called the "roots." In Visual Basic, you can write a program or function that prompts the user to enter the a, b and c values, find the roots and then display the values on the form.
Open a new Visual Basic program. Double-click the "Button" tool to add Button1 to the form. Double-click the "Label" tool twice to add Label1 and Label2 to the form.
Video of the Day
Double-click "Button1" on the form to open the code window. Type the following code:
Dim a As Decimal = InputBox("Enter A: ") Dim b As Decimal = InputBox("Enter B: ") Dim c As Decimal = InputBox("Enter C: ") Quadratic(a, b, c)
The first three lines prompt the user for the values of the constants. It then calls a sub called "Quadratic" and passes the constants as arguments to it.
Insert the cursor outside of the Button1 sub. Type the following code:
Private Sub Quadratic(ByVal a As Decimal, ByVal b As Decimal, ByVal c As Decimal) Dim roots(1) As String Dim x1, x2, disc As Decimal disc = b ^ 2 - 4 * a * c
The first line creates the Quadratic sub and accepts three arguments. It then defines an array with two items for the two roots. It then creates three decimal variables and assigns the value of the discriminant, which determines the number of roots the quadratic equation has.
Type the following code:
If disc >= 0 Then x1 = (-b + Math.Sqrt(disc)) / (2 * a) x2 = (-b - Math.Sqrt(disc)) / (2 * a) roots(0) = x1.ToString roots(1) = x2.ToString Else roots(0) = "(-" & b.ToString & "+Sqrt(" & disc.ToString & "))/(2_" & a.ToString & ")" roots(1) = "(-" & b.ToString & "-Sqrt(" & disc.ToString & "))/(2_" & a.ToString & ")" End If
The "if" function checks to see if the value of the discriminant is greater than or equal to zero, which means the equation has one or two roots. It then solves for x. If the discriminant is less than zero, the equation has no real roots and the "else" portion executes, which displays the complex roots equations.
Type the following code:
Label1.Text = roots(0) Label2.Text = roots(1) End Sub
These lines of code simply display the roots on the labels and then close the Quadratic sub's code block.
Save the Visual Basic program. Press "F5" to run it.