我想让我的程序执行,直到我手动退出它

时间:2015-08-08 21:38:28

标签: vb.net loops iteration

我使用vb创建了一个控制台程序 。 Net计算输入的数字因子,但它只在我退出之前执行一次,如何让程序运行直到用户想要退出? 这是我使用的代码

Module factorial 

 

    Dim factorial = 1, i, num As Integer

    Sub Main()

        Console.Write("Enter a number to find a factorial of it : ")

        num = Console.ReadLine()

 

        factorial = 1

        For i = 1 To num

            factorial = factorial * i

        Next

 

        Console.WriteLine("Factorial of {0} is {1}", num, factorial)

 

       

 

    End Sub

 

End Module

2 个答案:

答案 0 :(得分:1)

Console.ReadKey()将允许您让程序等待按任意键。

  

Console.ReadKey Method

如果你需要你的程序计算越来越多的阶乘,你应该将所有代码包装成无限循环:

Do
    Something
Loop

答案 1 :(得分:1)

要处理来自用户的多个输入,您需要将代码放在循环中。您需要一种方式让用户指出它的完成时间(例如输入"退出"而不是数字。

在将用户输入的字符串转换为Integer之前,您还应确保该字符串有效。您可以使用Integer.TryParse

来完成此操作

最后,你应该考虑阶乘是非常大的可能性。对于阶乘使用Long而不是Integer会有所帮助,但是阶乘可能仍然太大,因此您可以使用Try / Catch检查溢出并发送错误消息。如果您想处理任何大小的数字,可以研究BigInteger

Module factorial
    Sub Main()
        Do
            Console.Write("Enter a number to find its factorial, or Quit to end the program:")
            Dim inString As String = Console.ReadLine
            If inString.ToUpper = "QUIT" Then Exit Sub

            Dim num As Integer
            If Integer.TryParse(inString, num) Then
                Dim factorial As Long = 1
                Try
                    For i As Integer = 2 To num
                        factorial *= i
                    Next
                    Console.WriteLine("Factorial of {0} is {1}", num, factorial)
                Catch ex As OverflowException
                    Console.WriteLine("Factorial of {0} is too large", num)
                End Try
            End If
        Loop
    End Sub
End Module
相关问题