“确保你没有除以零”错误Visual Basic express

时间:2014-11-12 14:56:41

标签: vb.net

我正在使用Visual Basic express 2010.I想要创建一个要求数字的程序,并在给出0时停止。然后我要检查所有值以找到最小值,最大值是平均值和总和我有那个代码:

Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim total As Integer
        total = 0
        Dim average As Integer
        average = 0
        Dim loops As Integer
        loops = 0
        Dim max As Integer
        max = 0
        Dim min As Integer
        min = Val(InputBox("Give me the first number"))
        Dim number As Integer
        number = Val(InputBox("Give me a number"))
        Do Until number = 0
            loops = loops + 1
            If number < min Then
                min = number
            ElseIf number > max Then
                max = number
            End If
            total = number + total

        Loop
        average = total / loops
        MsgBox(total)
    End Sub
End Class

当我点击F5时,它会调出屏幕。在前2个输入框后,程序崩溃了。有什么想法吗? enter image description here

2 个答案:

答案 0 :(得分:0)

看看你的循环:

Do Until number = 0
    loops = loops + 1
    If number < min Then
        min = number
    ElseIf number > max Then
        max = number
    End If
    total = number + total
Loop

它会持续到number为0,但永远不会修改number。因此,如果它不是0,那么它将永远为0.因此,循环将无限期地继续。在那个循环中,你这样做:

loops = loops + 1

由于loopsInteger,因此它的范围相当有限。一旦达到MaxInt的值,您就不能再添加它了。因此,下次添加时,您会看到异常。

您需要在循环中修改number才能完成。

请注意&#34;除以零&#34;部分实际上并不是您所看到的错误消息的一部分。它只是Visual Studio向您展示的一个建议,因为除以零是此错误的常见原因。这次不是错误的来源。

答案 1 :(得分:0)

嘿看看这段代码。你遇到了问题,因为号码没有改变。

Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim total As Integer
        total = 0
        Dim average As Integer
        average = 0
        Dim loops As Integer
        loops = 0
        Dim max As Integer
        max = 0
        Dim min As Integer
        min = Val(InputBox("Give me the first number"))
        Dim number As Integer
        number = Val(InputBox("Give me a number"))
        Do Until number = 0
            loops = loops + 1
            If number < min Then
                min = number
            ElseIf number > max Then
                max = number
            End If
            total = number + total
            number = Val(InputBox("Give me a number"))
        Loop
        average = total / loops
        MsgBox(total)

    End Sub
End Class