2015-08-08 85 views
0

我已经创建了一个控制台程序,使用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 

回答

1

Console.ReadKey()将让你做出程序等待按下任意键的代码。

Console.ReadKey Method

如果你需要你的程序计算越来越多的阶乘,你应该换所有的代码放到无限循环这样的:

Do 
    Something 
Loop 
1

要处理多个输入用户,你需要把你的代码放在一个循环中。您需要一种方法让用户指出是时候完成了(例如通过键入“退出”而不是数字)

您还应该确保用户输入的字符串在转换为整数,你可以通过使用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 
相关问题