我必须为学校制作计算器。按钮应该在单击时在文本框中构建一个字符串,然后当按下=按钮时,将根据数字和操作计算答案。我不知道如何从字符串中取数字来计算它们。例如,如果我按" 2 + 2 ="如何将它们作为整数一起添加,以便输出为4?任何帮助表示赞赏。这是我到目前为止所拥有的
<head>
<script runat="server">
Dim value_all As String = "0"
Public Shared first_value As Integer
Public Shared second_value As Integer
Public Shared operator1 As Integer
Sub fillvalue(buttonvalue As Object, e As EventArgs)
value_all = lbl1.Text & buttonvalue.Text
lbl1.Text = value_all
End Sub
sub clear(s as Object, e as EventArgs)
lbl1.Text =""
End Sub
'here is where i want to do the math
Sub math(buttonvalue As Object, e As EventArgs)
If value_all.Contains("+") Then
lbl1.Text = buttonvalue.text + buttonvalue.text
ElseIf value_all.Contains("-") Then
lbl1.Text = first_value - second_value
ElseIf value_all.Contains("*") Then
lbl1.Text = first_value * second_value
ElseIf value_all.Contains("/") Then
lbl1.Text = first_value / second_value
End If
End Sub
</script>
</head>
<body>
<form id="Form1" runat="server">
<h3><asp:textbox id="lbl1" runat="server" /></h3>
<asp:Button ID="Button1" OnClick="fillvalue" Text="1" value="1" runat="server" />
<asp:Button ID="Button2" OnClick="fillvalue" Text="2" value="2" runat="server" />
<asp:Button ID="Button3" OnClick="fillvalue" Text="3" value="3" runat="server" />
<asp:Button id="Buttonadd" Text="+" runat="server" OnClick="fillvalue" value="+" />
<br />
<asp:Button ID="Button4" OnClick="fillvalue" Text="4" value="4" runat="server" />
<asp:Button ID="Button5" OnClick="fillvalue" Text="5" value="5" runat="server" />
<asp:Button ID="Button6" OnClick="fillvalue" Text="6" value="6" runat="server" />
<asp:Button ID="Buttonsub" OnClick="fillvalue" Text="-" runat="server" value="-" />
<asp:Button ID="Button7" OnClick="fillvalue" Text="7" value="7" runat="server" />
<asp:Button ID="Button8" OnClick="fillvalue" Text="8" value="8" runat="server" />
<asp:Button ID="Button9" OnClick="fillvalue" Text="9" value="9" runat="server" />
<asp:Button ID="Buttonmult" OnClick="fillvalue" Text="*" runat="server" value="*"/>
<br />
<asp:Button ID="Buttoneq" OnClick="math" Text="=" value="=" runat="server" />
<asp:Button ID="Buttonclr" OnClick="clear" Text="clear" runat="server" />
<asp:Button ID="Buttondiv" OnClick="fillvalue" Text="/" value="/" runat="server" />
</form>
</body>
答案 0 :(得分:0)
要将字符串转换为数字,您只需使用以下内容:
Dim inputAsNumber As Integer = Integer.Parse("123")
请注意Parse会在某些条件下抛出异常(如下所示)。根据您的需要,Int32.TryParse可能是更好的选择。
'All of these throw an exception:
Dim inputAsNumber1 As Integer = Integer.Parse("ABC") 'Not a number
Dim inputAsNumber2 As Integer = Integer.Parse("") 'Also not a number
Dim inputAsNumber3 As Integer = Integer.Parse(Nothing) 'Input is null
Dim inputAsNumber4 As Integer = Integer.Parse("123456789123456789") 'Overflow (too big)
答案 1 :(得分:0)
此处无需转换任何数字,您可以使用datatable class来评估使用其compute function存储为字符串的数学表达式...例如:
Dim result = New DataTable().Compute("1 + 2 + 3", Nothing)
'result is equal to 6