首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Basic do while循环和if do语句

Basic do while循环和if do语句
EN

Stack Overflow用户
提问于 2014-11-10 05:13:32
回答 2查看 1.1K关注 0票数 0

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

  • 如果数字是偶数,除以2。
  • 否则,将该数字乘以3并添加1。
  • 使用结果编号重复此过程,并继续重复该过程,直到到达数字1为止。
  • 到达数字1后,程序应该显示需要执行多少步。

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

代码语言:javascript
复制
 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

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

EN

回答 2

Stack Overflow用户

发布于 2014-11-10 05:43:33

您可以使用下面的代码来实现算法,您不会更改inputnum的值,这就是为什么您不能像预期的那样获得输出

代码语言:javascript
复制
    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."
票数 0
EN

Stack Overflow用户

发布于 2014-11-10 05:53:07

试试这个:

代码语言:javascript
复制
    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."
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26837181

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档