關於vb加的小問題

2009-01-03 10:48 am
Dim n1, n3, ans As Integer
Dim n2 As String
Public Sub aaa()
n1 = InputBox("Enter num1", "num1")
n2 = InputBox("Enter +-*/", "num2")
n3 = InputBox("Enter num3", "num3")
Call cshun(n1, n2, n3)
Call result
End Sub
Private Sub cshun(n1, n2, n3)
If n2 = "-" Then
ans = n1 - n3
ElseIf n2 = "/" Then
ans = n1 / n3
ElseIf n2 = "*" Then
ans = n1 * n3
Else
ans = n1 + n3
End If
End Sub
Private Sub result()
MsgBox ("the answer is " & Str(ans))
End Sub

3/3=1,3-3=0,3*3=9冇問題,但3+3=33有問題啦 who help me

回答 (2)

2009-01-03 6:42 pm
✔ 最佳答案
I ran the program, and I got 6 for an answer. This is what I did, basically no change from your program apart from adding a button to initiate the operation. The 33 as an answer is usually a result of concatenation of two strings (Java would have done that). Here is what I did, and PM me if you need more information.

Dim n1, n3, ans As Integer

Dim n2 As String

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Call aaa()
End Sub


Public Sub aaa()
n1 = InputBox("Enter num1", "num1")
n2 = InputBox("Enter +-*/", "num2")
n3 = InputBox("Enter num3", "num3")
Call cshun(n1, n2, n3)
Call result()
End Sub

Private Sub cshun(ByVal n1, ByVal n2, ByVal n3)
If n2 = "-" Then

ans = n1 - n3
ElseIf n2 = "/" Then

ans = n1 / n3
ElseIf n2 = "*" Then

ans = n1 * n3
Else

ans = n1 + n3
End If

End Sub

Private Sub result()
MsgBox("the answer is " & Str(ans))
End Sub

2009-01-03 6:48 pm
於vb語言中, +這個operator有兩個意義. 1: 數學的加; 2: string concatation, 即將兩串文字串在一起, 所以3+3的結果會變為33.
那什麼時候會做架, 什麼時候會做string cancat呢? 那就要看你的將什麼資料類型加在一起了. 若其中一個是數字, 系統會先密認作數字的加, 但不成功的話就當作string concat; 若兩個都是文字, 就自動密認為string concat了.
由於你cshun這個function, 沒有declare是什麼資料類型, 則會密認作object看, 而系統亦會當作儲存object的字串 (就算是數字) 都會當作string的資料類型. 所以往後計算會出現錯誤.
最簡單更改方式是將該function的定義改為如下;
Private Sub cshun(n1 as integer, n2 as integer, n3 as integer)
.......
end sub


收錄日期: 2021-04-13 16:20:38
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20090103000051KK00248

檢視 Wayback Machine 備份