简体   繁体   中英

How can I make this VB program recursive?

I need to use recursion in this program for a school project. The program checks if the number inputted is a real number (in this case defined by a number with a decimal with the characters 0-9 (eg 56.7). How would I make the function recursive?

Thanks :-)

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

Given that this is a homework assignment, I'm not going to write the code out for you. But I will say this -- there are a couple of ways to set this up. One straightforward way would be to pass the string (of the number) to CheckNumber and then check the first character -- if it's numeric, call CheckNumber again with the remainder of the string (everything minus what you just checked). If it's not numeric, return false. You'll need a special case to handle the very last character -- if it's numeric, then return true. If you propagate the boolean response properly, your recursion should unwind itself at the end with the right answer.

Good luck!

You should call the CheckNumber function from within itself, that is a recursion. Learn more about recursion here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM