Public Class Form1
Dim i
Dim str1
Dim str2
Dim ans As String
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim n As Integer = InputBox("請輸入一個數值")
'求正數因數
For i = 1 To n
If n Mod i = 0 Then
str1 = str1 & i & " "
End If
Next
Dim factor() As String = Split(str1, " ")
Dim factornum As Integer = UBound(factor)
If factornum = 2 Then
ans = "這是一個質數。"
Else
ans = "這是一個合數。"
End If
'求負數因數
Dim factor2() As String = Split(str1, " ")
For i = 0 To UBound(factor2)
factor2(i) = "-" & factor2(i)
str2 &= factor2(i) & " "
Next
str2 = Strings.Left(str2, Len(str2) - 3)
MsgBox(ans & vbCrLf & "這個數字的正因數包含:" & str1 & vbCrLf & "這個數字的負因數包含:" & str2)
End
End Sub
End Class
-------------------
另解:
'UBound函數功能為求出該陣列的個數,因For迴圈從0開始,因此會重複迴圈一次,故,我們可以改為UBound(factor2) - 1,回歸到原陣列個數,如使用這種方式,則可以省去在最後輸出前再進行一次去尾的動作。
Dim factor2() As String = Split(str1, " ")
For i = 0 To UBound(factor2) - 1
factor2(i) = "-" & factor2(i)
str2 &= factor2(i) & " "
Next
沒有留言:
張貼留言