2015-08-08 44 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 
相關問題