十进制溢出VB 2012

时间:2014-02-22 08:57:49

标签: vb.net

Visual Studios帮助指南说它以十进制存储的最大可能值为79,228,162,514,264,337,593,543,950,335每当我输入一个大数字时程序什么都不做,所以我想为用户显示一条错误消息,要求他们输入一个较小的值或以某种方式检测溢出。我尝试使用

If lengtha = 79,228,162,514,264,337,593,543,950,335 Then
                MsgBox("Can not compute, try a smaller value.")
            End If

但它没有成功。这是迄今为止的代码。

Class MainWindow 

Private Sub Button_Click(sender As Object, e As RoutedEventArgs) Handles Calculate.Click
    Dim length As String = LengthTextBox.Text
    If IsNumeric(length) Then


    Else
        MsgBox("The value entered in legnth is not numeric, please enter a numeric value.", MsgBoxStyle.OkOnly, "Error")

    End If

    Dim width As String = WidthTextBox.Text
    If IsNumeric(width) Then


    Else
        MsgBox("The value entered in width is not numeric, please enter a numeric value.", MsgBoxStyle.OkOnly, "Error")

    End If

    Try
        Dim lengtha As Decimal = Decimal.Parse(length)
        If lengtha < 0 Then
            MsgBox("Length can not be negative.")
            Return
        End If

        Dim widtha As Decimal = Decimal.Parse(width)
        If widtha < 0 Then
            MsgBox("Width can not be negative.")
            Return
        End If
        Dim calculations1 As Decimal = lengtha * widtha
        AnswerLabel.Content = "Area: " + calculations1.ToString
        Dim calculations2 As Decimal = lengtha * 2 + widtha * 2
        answerLabel2.Content = "Perimeter: " + calculations2.ToString
    Catch ex As Exception

    End Try
End Sub

结束班

3 个答案:

答案 0 :(得分:2)

请停止使用IsNumeric检查字符串是否可以被视为数字 IsNumeric是VB6和its disandvantage are numerous的遗物,众所周知。

您应该使用Decimal.TryParse检查隐藏在字符串中的潜在十进制值并将其转换为十进制类型,并且不要使用空的try / catch来隐藏异常。
这样,如果您的代码中有错误,您将很难诊断它。

让我尝试一种不同的方法

Private Sub Button_Click(sender As Object, e As RoutedEventArgs) Handles Calculate.Click

    Dim lengtha As Decimal 
    Dim length As String = LengthTextBox.Text
    If Not Decimal.TryParse(length, legtha) Then
        MsgBox("The value entered in length is not numeric, please enter a numeric value.", MsgBoxStyle.OkOnly, "Error")
        Return
    End If
    If lengtha < 0 Then
         MsgBox("Length can not be negative.")
         Return
    End If

    Dim widtha As Decimal 
    Dim width As String = WidthTextBox.Text
    If Not Decimal.TryParse(width, widtha) Then
        MsgBox("The value entered in width is not numeric, please enter a numeric value.", MsgBoxStyle.OkOnly, "Error")
        Return
    End If
    If widtha < 0 Then
         MsgBox("Width can not be negative.")
         Return
    End If

    Try
        Dim calculations1 As Decimal = lengtha * widtha
        AnswerLabel.Content = "Area: " + calculations1.ToString
        Dim calculations2 As Decimal = lengtha * 2 + widtha * 2
        answerLabel2.Content = "Perimeter: " + calculations2.ToString
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
End Sub

还有两个可能的问题需要注意。

首先,如果您的用户按照您所示的方式键入带有千位分隔符的数字,那么您需要使用不同版本的TryParse,即允许传递NumberStyle枚举和NumericFormatInfo

的版本。
If Not Decimal.TryParse(length, _
        NumerStyles.AllowThousands Or NumberStyles.AllowDecimal,  _
        CultureInfo.CurrentCulture, legtha) Then

其次,为获取calculations1calculations2的值而执行的多部分可能会导致某个值太大而无法用十进制变量表示,并且您可能会遇到溢出异常。如果不需要输入Width和Length值的上下文,就很难解决这个问题。也许检查字符串字符的最大长度可以避免它

答案 1 :(得分:0)

如果lengtha = 79,228,162,514,264,337,593,543,950,335那么                 MsgBox(&#34;无法计算,请尝试较小的值。&#34;)             结束如果

仅检查完全匹配。我想你也想要更大的数字。 也许您可以检查字符数是否小于30,前两个字符是否小于79。

同时确保文化信息正确,因为有些国家/地区使用。而另一种方式。

答案 2 :(得分:0)

这可能不是非常优雅的代码,但也许你可以更好地理解它。尝试使用Decimal.Tryparse解析字符串并相应地执行操作。有关详细说明,请参阅代码注释。

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    'Save input strings in easier variables
    Dim inputLength As String = TextBox1.Text
    Dim inputWidth As String = TextBox2.Text

    Dim length, width As Decimal 'These will hold our results

    'Tryparse tries to convert the string to decimal. Returns true if successful
    'and false if not successful. If true then the result-field will also hold the
    'converted value
    Dim IsLengthOk As Boolean = Decimal.TryParse(inputLength, length)
    Dim IsWidthOk As Boolean = Decimal.TryParse(inputWidth, width)

    'Create an error message if either of the values is invalid and exit the sub if so
    Dim ErrorString As New System.Text.StringBuilder
    If Not IsLengthOk Then ErrorString.AppendLine("The value you entered for length is not a valid number.")
    If Not IsWidthOk Then ErrorString.AppendLine("The value you entered for width is not a valid number.")
    If Not IsLengthOk OrElse Not IsWidthOk Then
        MessageBox.Show(ErrorString.ToString, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        Exit Sub
    End If

    'Now check the values if they are larger than zero (you could also just use
    'Math.Abs(length) to make the numbers positive
    IsLengthOk = (length > 0) 'assign the result of the comparison to the boolean variables
    IsWidthOk = (width > 0)

    'Again, create error messages if there are errors
    ErrorString.Clear()
    If Not IsLengthOk Then ErrorString.AppendLine("Length must be larger than zero!")
    If Not IsWidthOk Then ErrorString.AppendLine("Width must be larger than zero!")
    If Not IsLengthOk OrElse Not IsWidthOk Then
        MessageBox.Show(ErrorString.ToString, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        Exit Sub
    End If

    'Calculate now your results and output them
    Dim calculations1 As Decimal = length * width
    AnswerLabel.Content = "Area: " + calculations1.ToString
    Dim calculations2 As Decimal = length * 2 + width * 2
    answerLabel2.Content = "Perimeter: " + calculations2.ToString
End Sub