VB.NET控制台应用程序|使用用户输入的数字显示因子

时间:2016-11-16 00:38:15

标签: vb.net loops optimization

我的代码工作正常,但需要一些优化而不需要任何额外的变量或循环。 输出应如下所示:5 X 4 X 3 X 2 X 1 = 120

Private Sub FactorialCalculation()

    Dim Number, Factorial As Integer

    Console.WriteLine("Please enter a number")
    Number = CInt(Console.ReadLine)
    Factorial = 1

    Console.WriteLine("Your number is " & Number)

    If Number > 0 Then
        Console.Write(Number & " X ")
        For Count As Integer = 1 To Number
            If (Number - Count) > 0 And (Number - Count) <> 1 Then
                Factorial *= Count
                Console.Write("{0} X ", Number - Count)
            ElseIf (Number - Count) = 0 Then
                Factorial *= Count
            ElseIf (Number - Count) = 1 Then
                Factorial *= Count
                Console.Write(Number - Count)
            End If

        Next
        Console.WriteLine(" = {0}", Factorial)
    Else
        Console.WriteLine("Please enter a positive number greater than 0")
    End If
End Sub

1 个答案:

答案 0 :(得分:1)

与你的相似的完整示例。关键是要使用一个功能。我选择了递归

Sub Main()
    Console.WriteLine("Please enter a number")
    Dim number As Long
    If Long.TryParse(Console.ReadLine, number) AndAlso number >= 0 Then
        Console.WriteLine("Your number is " & number)
        Try
            Console.WriteLine("{0} factorial = {1}", number, fact(number))
        Catch ex As Exception
            Console.WriteLine(ex.Message)
        End Try
    Else
        Console.WriteLine("Please enter a positive number greater than 0")
    End If
    Console.ReadLine()
End Sub

Private Function fact(ByVal number As Long) As Long
    Return If(number = 0, 1, number * fact(number - 1))
End Function

也可以限制为数字&lt; = 20,因为Int64似乎无法容纳事实21或更多。