2017-06-29 33 views
0

我對於Visual Basic來說真的很陌生。所以我試圖在Visual Basic中創建一個Windows窗體應用程序,它從兩個文本框中獲取兩個數字。在運行應用程序時,我試圖計算2 + 3,但得到23。怎麼了?試圖在Visual Basic中做2 + 3。改爲23而不是

Public Class CalcForm 
    Private Sub sumBtn_Click(sender As Object, e As EventArgs) Handles sumBtn.Click 
     Dim res As Integer 
     res = firNum.Text + secNum.Text 
     Convert.ToDecimal(res) 
     resultNum.Text = res 
    End Sub 
End Class 
+2

您添加secnum.text這是字符串。添加:'res = convert.ToInt32(firNum.Text)+ convert.ToInt32(secNum.Text)' – Mederic

+0

此代碼中的'Convert.ToDecimal(res)'行不做任何事。你希望它會做什麼? – Enigmativity

+0

非常感謝,讓我試試看。 –

回答

7

的問題是要添加兩個字符串:

firNum.Text + secNum.Text 

這不會做加法。

使用數字來代替:

Dim res As Decimal 
res = Convert.ToDecimal(firNum.Text) + Convert.ToDecimal(secNum.Text) 
resultNum.Text = res 

我使用的小數,因爲你在哪裏使用它,以及之前。 對於轉換工作,你需要確保你的文本框只使用數字。

可以使用例如檢查:IsNumeric()

+0

恭喜1000個聲望! - 哎呀......我毀了這個平靜......;) –

+1

@VisualVincent Nooooooooooooooooooooooo你** ** **!哈哈哈感謝uptvote:p – Mederic

0
Public Class CalcForm 
    Private Sub sumBtn_Click(ByVal sender As Object, ByVal e As EventArgs) Handles sumBtn.Click 
     Dim res As Integer 
     Dim first, second As Integer 
     If Integer.TryParse(firNum.Text, first) AndAlso Integer.TryParse(secNum.Text, second) Then 
      res = first + second 
      resultNum.Text = res.ToString() 
     Else 
      MessageBox.Show("Invalid input") 
     End If 
    End Sub 
End Class 
+0

謝謝,但你能告訴什麼5行意味着什麼? –

+0

如果每個框中的文本都成功轉換爲一個'Integer',然後添加它們並在'resultNum'中顯示輸出,否則顯示一個'MessageBox' –

+0

Integer.TryParse嘗試將第一個參數轉換爲Integer。如果成功,結果將存儲在參數2中,並且函數返回True。否則它將返回false –

0

我認爲這是正常的,你需要firstNum和SECNUM轉換爲整數,否則你只是concatening兩個字符串值:

res = firNum.Text + secNum.Text 

將字符串轉換爲整數使用CInt()

那麼你應該能夠做到2 + 3

0

「5」就是5

不同,您可以使用一個Func,這樣即使你有一些字符串後,將其轉換爲十進制只要它是一個小數而不是一個字符。

Dim addTogether As Func(Of Decimal, Decimal, Decimal) = Function(num1, num2) num1 + num2 
    Try 
     Console.WriteLine(addTogether("5", 5)) ''output 10 even with a string as the first character 
    Catch ex As Exception 
     Console.WriteLine(ex.Message) 
    End Try