【问题标题】:How can I make this VB program recursive?如何使这个 VB 程序递归?
【发布时间】:2015-10-21 15:29:20
【问题描述】:

我需要在这个程序中为一个学校项目使用递归。程序检查输入的数字是否为实数(在这种情况下,由带有字符 0-9 的小数点定义的数字(例如 56.7)。如何使函数递归?

谢谢:-)

Module Real_Numbers

    Sub Main()
        Dim number As String
        Dim check As Boolean
        Console.WriteLine("Enter a number to check if it is a real number:")
        number = Console.ReadLine()
        check = CheckNumber(number)

        If check = True Then
            Console.WriteLine("The number is a real number")
        Else
            Console.WriteLine("The number is not a real number")
        End If
        Console.ReadLine()

    End Sub

    Function CheckNumber(ByVal number As String) As Boolean
        Dim current As Char
        For i As Integer = 0 To number.Length - 1
            current = number.Substring(i, 1)
            If current = "." Then
                ' Do nothing
            Else
                If IsNumeric(current) Then
                    ' Do nothing
                Else
                    Return False
                End If
            End If

        Next

        Return True

    End Function

End Module

【问题讨论】:

  • 我不明白你为什么需要递归。你能解释一下吗?
  • 我也认为这完全是垃圾,但学校让我们这样做......
  • 您不只需要IsNumeric() 函数吗?根据您的要求,听起来您需要确定是否给定了一些用户输入-确定该输入是否为实数。 IsNumeric() 函数就是这样做的——不需要递归。除非我忽略了某些事情,否则请告诉我,以便我尝试提供帮助
  • 你能准确地发布你被要求做的事情吗,因为听起来你没有遵守简报
  • @HardTacos IsNumeric 单独是行不通的,因为它为负值返回 True,这不是实数

标签: vb.net function recursion methods procedure


【解决方案1】:

鉴于这是一项家庭作业,我不会为你编写代码。但我会这么说——有几种方法可以设置它。一种直接的方法是将字符串(数字)传递给 CheckNumber,然后检查第一个字符 - 如果它是数字,则使用字符串的其余部分(所有内容减去您刚刚检查的内容)再次调用 CheckNumber。如果不是数字,则返回 false。您需要一种特殊情况来处理最后一个字符——如果它是数字,则返回 true。如果你正确地传播布尔响应,你的递归应该在最后以正确的答案展开。

祝你好运!

【讨论】:

  • 您可能需要注意小数点(或者更好的小数点分隔符)。此外,您不想要超过其中之一。
【解决方案2】:

您应该从自身内部调用 CheckNumber 函数,即递归。详细了解递归here

【讨论】:

    猜你喜欢
    • 2011-10-23
    • 2022-12-03
    • 2013-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-01
    • 2012-05-04
    • 2017-02-20
    相关资源
    最近更新 更多