2014-12-13 49 views
0

我有這個可視化的基本代碼來接收用戶輸入並打印出許多素數。例如,如果用戶輸入5,輸出應該是:1,3,5,7,11,但我發現it.Here困難是我的代碼:如何在Visual Basic(表單)中打印N個素數?

Dim i, n, input, currentPrime As Integer 
     Dim Wrap As String = Chr(10) & Chr(13) 
     input = txtInput.Text 
     currentPrime = 1 
     txtAns.Text = "Prime Numbers are : " & Wrap 
     Do While (currentPrime <= input) 
      For i = currentPrime To input 
       For j = 2 To Fix(i/2) + 1 
        If i Mod j = 0 Then 
         n = 1 
        End If 
       Next 
       If n = 1 Then 
        n = 0 
       Else 
        txtAns.Text = txtAns.Text & Wrap & i & " is a prime number " & Wrap 
       End If 
      Next 
      currentPrime += 1 
     Loop 
+0

我有關於我的代碼的問題。我發現它很困難。我的輸出應該是如果用戶輸入5,輸出應該是:1,3,5,7,11。但我的是直到499 :( – 2014-12-13 02:24:00

+0

可能重複[如何在Vb.net中打印N個素數(形式)?](http://stackoverflow.com/questions/27446434/how-to-print-n-number-of-primes-in-vb-net-forms) – AJDev 2014-12-13 02:57:41

+0

我該如何開始我的序列2? – 2014-12-13 06:12:24

回答

0

嘗試......

Dim i, n, input As Integer 
    Dim Wrap As String = Chr(10) & Chr(13) 
    input = txtInput.Text 
    Dim found = 0 
    Dim output = "Prime Numbers are : " & Wrap 
    While found < input 
     i = i + 1 
     For j = 2 To Fix(i/2) + 1 
      If i Mod j = 0 Then 
       n = 1 
      End If 
     Next 
     If n = 1 Then 
      n = 0 
     Else 
      output = output & Wrap & i & " is a prime number " & Wrap 
      found = found + 1 
     End If 
    End While 
    txtAns.Text = output 
+0

哦它的工作原理!謝謝你這麼多:)這是我的主要問題通過列出前六個素數:2,3,5,7,11和13,我們可以看到第六個素數是13. 什麼是10 001號素數? – 2014-12-13 03:43:56

+0

我可以在哪裏插入我的驗證? Dim letters As Boolean If txtAns.Text =「」or letters = IsNumeric(txtAns.Text)Then MessageBox.Show(「請輸入數字!」,「信息」,MessageBoxButtons.OK,MessageBoxIcon.Warning) txtAns .Clear() – 2014-12-13 05:09:54

+0

如果驗證失敗,則應將驗證放在例程的頂部,並使用Exit Sub。如果它是正確的,請將其標記爲答案。 – Spock 2014-12-13 05:53:44