为什么这不起作用?我找不到任何解决方案

时间:2014-08-27 18:46:15

标签: vb.net

此程序将要求用户输入4次,然后显示3个带有3个不同答案的消息框。每个答案由2个不同的数字(范围)组成,但我无法运行它,因为我无法使用该功能。

我的主要问题是功能。变量a,b,c,d将由用户提供,x将在程序开始时由我提供。我无法运行程序,因为函数用蓝线加下划线。

Dim a As Integer
Dim b As Integer
Dim c As Integer
Dim d As Integer

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    Dim a As Integer
    Dim b As Integer
    Dim c As Integer
    Dim d As Integer


Function f(x As Double) As Double
    f = (a * x ^ 3) + (b * x ^ 2) + (c * x) + d
    Exit Function
End Function
Sub incremental()

    Dim left As Double
    Dim right As Double
    Dim product As Double
    Dim counter As Integer

    counter = 0
    left = -10
    right = -9.7
    product = 1

    a = InputBox("Please provide a coefficient for x^3.", "title", 0)
    b = InputBox("Please provide a coefficient for x^2.", "title", 0)
    c = InputBox("Please provide a coefficient for x^1.", "title", 0)
    d = InputBox("Please provide a coefficient for x^0.", "title", 0)

    Do While product > 0
        product = f(left) * f(right)

        If product > 0 Then
            left = right
            right = left + 0.3

        Else
            If counter = 0 Then
                MsgBox("Your approximate root is  " & left & "  and  " & right & ".")
                counter = counter + 1
                product = 1
                left = right
                right = left + 0.3

            ElseIf counter = 1 Then
                MsgBox("Your approximate root is  " & left & "  and  " & right & ".")
                counter = counter + 1
                product = 1
                left = right
                right = left + 0.3

            Else : counter = 2
                MsgBox("Your approximate root is  " & left & "  and  " & right & ".")
                counter = 3

            End If

        End If

    Loop

End Sub

2 个答案:

答案 0 :(得分:4)

不确定这是否只是你的一个错别字或者这实际上是问题,但你错过了“End Sub”部分:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    Dim a As Integer
    Dim b As Integer
    Dim c As Integer
    Dim d As Integer

' --------------------
End Sub  ' <----------
' --------------------


Function f(x As Double) As Double

这就是Function以蓝色加下划线的原因。

但这不会修复您的代码。它仍然被打破,因为您不了解面向对象编程的基础知识。在这方面我没有什么可以提供给你的......它只是一个主题太大了。

例如,您已声明Button1_Click来处理按钮点击次数。您说abcd将由用户提供,但这似乎永远不会发生(您没有为它们分配任何内容)。然后,您结束该函数,导致abcd变量被删除(或者更确切地说,这些变量所保留的内存地址将被释放)

同时,您的函数f引用了名为abcd的变量,但从未声明它们。您似乎正在尝试使用Button1_Click函数中的变量,但Button1_Clickf是完全不同的上下文 - 它们无法访问彼此的变量。如果您想将abcd传递给f,则必须将这些值作为参数传递(f(x, a, b, c, d))或通过其他方式获取它们(例如将它们声明为对象级属性等)。

看起来这可能是编程家庭作业,所以除了“祝你好运”之外,我不会说除此之外的事情。

答案 1 :(得分:1)

正如Andrew Arnold所说:

roght = left + 0.3

应改为:

right = left + 0.3