基本做while while循环和if then语句

时间:2014-11-10 05:13:33

标签: vb.net loops visual-studio-2012 if-statement

我需要帮助创建这个程序。 我需要:编写一个程序来请求一个正整数作为输入,并执行以下算法。

  • 如果数字是偶数,则除以2.
  • 否则,将数字乘以3并加1。
  • 使用生成的数字重复此过程,并继续重复该过程,直到达到数字1。
  • 达到数字1后,程序应显示需要多少步骤。

现在我知道输出标签中的行是错误的,但不知道如何将步数放入其中。

 Private Sub calcButton_Click(ByVal sender As Object, ByVal e As EventArgs) Handles calcButton.Click

      Dim inputnum, output2, output3 As Integer

      inputnum = inputTextbox.Text

      Do
        If inputnum <> 1 Then
          If inputnum Mod 2 = 0 Then
            resultListbox.Items.Add(output2)
          Else
            resultListbox.Items.Add(output3)
          End If
        End If
        output2 = inputnum / 2
        output3 = ((inputnum / 3) + 1)
      Loop Until inputnum = 1
      outputLabel.Text = "It took " & inputnum & " steps to reach 1."

    End Sub

程序在列表框中不显示任何数字

2 个答案:

答案 0 :(得分:0)

您可以使用以下代码来实现算法,您不会更改inputnum的值,这就是您没有按预期获得输出的原因

    Dim iterationCount As Integer = 0 '<--- count the number of iteration
    Dim inputnum = inputTextbox.Text '<-- let it be 12
    Do
        If inputnum <> 1 Then
            If inputnum Mod 2 = 0 Then
                inputnum /= 2 '<-- If the number is even, divide it by 2.
                resultListbox.Items.Add(inputnum)
            Else
                inputnum = inputnum / 3 + 1 '<--- Otherwise, multiply the number by 3 and add 1.
                resultListbox.Items.Add(inputnum)
            End If
            iterationCount += 1 '<-- increment the iteration counter
        End If
    Loop Until inputnum = 1
   outputLabel.Text = "It took " & iterationCount & " steps to reach 1."

答案 1 :(得分:0)

试试这个:

    Dim inputnum As Integer
    Dim count As Integer = 0
    inputnum = inputTextbox.Text
    resultListbox.Items.Clear() 'clear the list for next input number
    While inputnum <> 1
        If inputnum Mod 2 = 0 Then                
            inputnum = inputnum / 2
            resultListbox.Items.Add(inputnum)
        Else
            inputnum = inputnum * 3 + 1
            resultListbox.Items.Add(inputnum)
        End If
        count = count + 1
    End While
    outputLabel1.Text = "It took " & count & " steps to reach 1."