【问题标题】:Visual Basic Temperature ConverterVisual Basic 温度转换器
【发布时间】:2011-08-25 05:39:23
【问题描述】:

我是 Visual Basic 的新手,我正在 Visual Studio 2010 中创建一个 aspx 温度转换器应用程序,用户可以在其中将数字输入到文本框中,通过下拉列表框选择温度类型,然后选择要使用的温度将其转换为单选按钮列表。我遇到的问题是当我尝试转换某些东西时出现错误。我收到错误“输入字符串的格式不正确”和“从字符串“F”到类型“布尔”的转换无效。”我尝试过嵌套 if..elseif..endif 语句,但是当我这样做时,它只会转换第一个 if 语句而没有别的。这是我为转换编写的代码。对此的任何帮助将不胜感激。谢谢。

 Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
    If (DropDownList1.SelectedValue = "F" & RadioButtonList1.SelectedValue = "F") Then
        Label1.Text = TextBox1.Text & "Fahrenheit=" & TextBox1.Text & "Fahrenheit"

    ElseIf (DropDownList1.SelectedValue = "F" & RadioButtonList1.SelectedValue = "C") Then
        Label1.Text = TextBox1.Text & "Fahrenheit=" & (TextBox1.Text * 1.8) + 32 & " Celsius"

    ElseIf (DropDownList1.SelectedValue = "F" & RadioButtonList1.SelectedValue = "K") Then
        Label1.Text = TextBox1.Text & "Fahrenheit=" & ((5 / 9) * (TextBox1.Text - 32) + 273) & " Kelvin"

    ElseIf (DropDownList1.SelectedValue = "C" & RadioButtonList1.SelectedValue = "C") Then
        Label1.Text = TextBox1.Text & "Celsius=" & TextBox1.Text & "Celsius"

    ElseIf (DropDownList1.SelectedValue = "C" & RadioButtonList1.SelectedValue = "F") Then
        Label1.Text = TextBox1.Text & " Celsius = " & (TextBox1.Text - 32) / 1.8 & " Fahrenheit"

    ElseIf (DropDownList1.SelectedValue = "C" & RadioButtonList1.SelectedValue = "K") Then
        Label1.Text = TextBox1.Text & " Celsius = " & (TextBox1.Text + 273) & " Kelvin"

    ElseIf (DropDownList1.SelectedValue = "K" & RadioButtonList1.SelectedValue = "K") Then
        Label1.Text = TextBox1.Text & "Kelvin=" & TextBox1.Text & "Kelvin"

    ElseIf (DropDownList1.SelectedValue = "K" & RadioButtonList1.SelectedValue = "F") Then
        Label1.Text = TextBox1.Text & "Kelvin=" & ((TextBox1.Text - 273) * 1.8) + 32 & "Fahrenheit"

    ElseIf (DropDownList1.SelectedValue = "K" & RadioButtonList1.SelectedValue = "C") Then
        Label1.Text = TextBox1.Text & "Kelvin=" & (TextBox1.Text - 237) & "Celsius"



    End If



End Sub

【问题讨论】:

  • 您可能希望 and 而不是 & 在条件中 - 这应该可以解决转换为布尔的错误。
  • @Rup 你应该发布你的答案,我后来才注意到。好像是你说的。
  • @Matt 我认为这还不完整——我认为它不会解决输入字符串错误。等等,也许那只是一张 CDbl……
  • 去掉了输入字符串错误,但是label1在转换时没有输出。
  • 没关系,我只是忘了重命名列表项。现在可以正常使用了,谢谢大家的帮助

标签: asp.net vb.net


【解决方案1】:

我认为这两个错误是:

  • 您在if 条件下使用& - 这应该是and
  • 您正在尝试直接对字符串执行算术 - 您需要先转换它,例如到双 CDbl(TextBox1.Text)

也就是说,可能有一些重构的空间:你可以例如只计算温度值,然后在底部组装字符串,再次分别测试那里的下拉列表,以便每个“Kelvin =”字符串只有一个副本,等等。

【讨论】:

  • +1 我可能会用嵌套的Select Case 结构替换长的If Else 结构。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多