首页 > 解决方案 > 函数不向主程序返回值(Visual Studio)

问题描述

我是 Visual Studio 的新手,我正在尝试为我的课程创建一个菜单,但是当我调用菜单函数时它会运行,但它不会将“UserChoice”返回到主程序中。

模块课程

Sub Main()

    Console.Title = "Coursework"

    Dim UserChoice As Integer


    Call Menu()

    If UserChoice = 1 Then
        Console.WriteLine("You have chosen the accuracy option. 
        Please enter the number you want to round up:")

        Dim NumberToRound As Long
        NumberToRound = Console.ReadLine()


        Call Menu()    ' By putting "Call Menu()" at the end of each choice we make a loop until the user has chosen option 5 which closes the program.
    End If


End Sub


Function Menu()
    Console.WriteLine("Please choose an option:

    1. Accuracy
    2. Quadratic equation
    3. Protein Sequence Segmentation
    4. Monte-Carlo Integration of a function
    5. Close the program                       ")

    Dim UserChoice As Integer
    UserChoice = Console.ReadLine()
    Return UserChoice
End Function

任何人都有任何想法为什么会这样?提前致谢。

标签: vb.net

解决方案


你只是忽略了你显然已经知道的东西。从您自己的代码中查看:

Dim UserChoice As Integer
UserChoice = Console.ReadLine()

那有什么作用?它声明一个变量,调用一个方法并将结果分配给变量。现在看看这个:

Dim UserChoice As Integer


Call Menu()

你看到那里有什么不同吗?您声明了一个变量并调用了一个方法,但由于某种原因,您认为该方法的结果会神奇地出现在变量中,而没有明显的原因。如果您希望一个变量有一个值,那么您必须将该值分配给它,并且您显然知道如何执行此操作,因为您在其他地方执行此操作。为什么这里应该不一样?

Dim UserChoice As Integer

UserChoice = Menu()

推荐阅读