计算VB.NET的问题

时间:2017-04-08 15:42:20

标签: vb.net visual-studio

我创建了一个程序,当有人在三个文本框中插入3个值并按下按钮时,它会显示代码的结果:

Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim d As Integer
    Dim p As Integer
    Dim y As Integer
    Dim v As Integer

    d = TextBox1.Text
    p = TextBox2.Text
    y = TextBox3.Text
    v = Label5
    v = d * (1 + (p / 100)) ^ y


End Sub

Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged

End Sub
End Class

问题是,当我按下按钮时,没有任何反应。如果你可以帮助我使用代码,那将是不错的

提前谢谢

2 个答案:

答案 0 :(得分:0)

您需要在执行数学运算之前将条目转换为数值,并且需要将结果分配给label5的“text”属性而不是控件。

这样的事情:

Dim d As Integer = Integer.Parse(TextBox1.Text)
Dim p As Integer = Integer.Parse(TextBox2.Text)
Dim y As Integer = Integer.Parse(TextBox3.Text)
Dim v As Integer = d * (1 + (p / 100)) ^ y

Label5.Text = v.ToString()

答案 1 :(得分:0)

看起来您没有将结果分配给任何在退出方法后保留值的内容。我假设Label5是您想要答案的地方。你也用整数除以100并将结果放到一个整数中,整数只会给你整数没有分数,我建议改用Double。此外,您应该在类的顶部使用Option Strict On,(来自链接)此"将隐式数据类型转换限制为仅扩展转换,禁止后期绑定,并禁止隐式输入,从而导致对象类型" ,它将帮助防止细微的错误进入您的代码。

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    Dim d As Integer
    Dim p As Integer
    Dim y As Integer
    Dim v As Double

    If Not Integer.TryParse(TextBox1.Text, d) Then
        ShowError(TextBox1.Name)
    End If
    If Not Integer.TryParse(TextBox2.Text, p) Then
        ShowError(TextBox2.Name)
    End If
    If Not Integer.TryParse(TextBox3.Text, y) Then
        ShowError(TextBox3.Name)
    End If

    v = d * (1 + (p / 100)) ^ y
    Label5.Text = v.ToString()

End Sub

Sub ShowError(control As String)
    MsgBox(control & " Input Error", MsgBoxStyle.Exclamation Or MsgBoxStyle.OkOnly, "Input Error")
End Sub