教學範例《9》… 解二次方程式AX^2+BX+C=0

表單設計與程式執行:
表單設計
執行畫面

控制項屬性資料:
Form1   : 調整表單視窗的大小,使Width和Height合乎適當大小。
Label1  : Caption = "A="
Label2  : Caption = "B="
Label3  : Caption = "C="
Label4  : Caption = "解一元二次方程式AX^2+BX+C=0"
Label5  : Caption = "判別式B^2-4AC="
Label6  : Caption = "根的性質"
Label7  : Caption = "X1 ="
Label8  : Caption = "X2 ="
Label9  : Caption = "機1-3 王小明製作"
Label10 : Caption = "學號:2902001"
Text1   : Text = "1"
Text2   : Text = "2"
Text3   : Text = "3"
Text4   : Text = ""
Text5   : Text = ""
Text6   : Text = ""
Text7   : Text = ""
程式碼列表:
Public A, B, C, D As Single

Private Sub Command1_Click()
  A = Val(Text1.Text)
  B = Val(Text2.Text)
  C = Val(Text3.Text)
'-------------------------------
  If B >= 0 Then
     G1$ = "+"
     Else
     G1$ = "-"
  End If
  If C >= 0 Then
     G2$ = "+"
     Else
     G2$ = "-"
  End If
'-------------------------------------------------------------------------
U$ = Str(A) + "X^2" + G1$ + Str(Abs(B)) + "X" + G2$ + Str(Abs(C)) + "= 0"
Label4.Caption = "一元二次方程式" + U$

D = B * B - 4 * A * C
Text4.Text = Str(D)

Select Case D
   Case Is >= 0
      X1 = -B / (2 * A) + Sqr(D) / (2 * A)
      X2 = -B / (2 * A) - Sqr(D) / (2 * A)
      If D > 0 Then Text5.Text = "有二不等實數根(實根)"
      If D = 0 Then Text5.Text = "有二相等實數根(重根)"
      Text6.Text = Str(X1)
      Text7.Text = Str(X2)
   Case Is < 0
     U = -B / (2 * A)
     V = Sqr(Abs(D)) / (2 * A)
     Text5.Text = "其解為共軛複根(虛根)"
     Text6.Text = Str(U) + "+" + Str(V) + "i"
     Text7.Text = Str(U) + "-" + Str(V) + "i"
   End Select

End Sub

Private Sub Command2_Click()
End
End Sub
程式解說:
學習重點:
 ˙學會多重選擇判斷結構Select Case的程式設計。
 ˙瞭解二次方程式的公式解法,與判斷式在程式中為關鍵角色。
 ˙應用Text4文字框顯示二次方程式,字串結合用法。
程式說明:
 (1)由文字框Text1,Text2,Text3分別輸入二次方程式係數A,B,C。 
 (2)判斷A,B,C的正負值;設定G1$,G2$的內容為"+"或"-"。 
  (3)判斷式 D=B*B - 4*A*C。
  (4)根據D值作 Select Case 多重判斷,在Text5顯是根的判斷結果。
  (5)Case Is >= 0 有二不等實數根(實根)或二相等實數根(重根)。
  (6)Case Is < 0 其解為共軛複根(虛根)。
  (7)Text6,Text7分別顯示兩根的值。
  (8)Command2按鈕,僅有一指令"End"為程式結束。