【问题标题】:How to count and output total number of loops in visual basic console application?如何在 Visual Basic 控制台应用程序中计算和输出循环总数?
【发布时间】:2016-09-02 02:10:50
【问题描述】:

我正在学习 Visual Basic,并编写了一个简单的 Visual Basic 控制台应用程序来执行“一半或三倍加一”计算,并且控制台应用程序可以工作,但我还想计算并显示运行循环的总数以达到解决方案。这是我的代码:

Sub Main()
    Dim n As Double
    Console.WriteLine("Enter a starting number.")
    n = Console.ReadLine()

    Do While n <> 1

        Do While n > 1

            If n Mod 2 = 0 Then
                n = n / 2
            Else
                n = (n * 3) + 1

            End If
            Console.WriteLine(n)
        Loop
        If n = 1 Then
            Console.WriteLine(
            n = Console.ReadLine()
        End If

    Loop



    Console.ReadLine()

End Sub

我似乎找不到任何可以计算和显示循环次数的内容。

【问题讨论】:

  • 添加一个计数器变量,在每次通过循环时递增,并使用 Console.WriteLine 输出它,就像您输出 n 一样。

标签: vb.net loops console console-application counter


【解决方案1】:

如果我没有误会你,问题就解决了 引入一个名为j的新变量,最终代码结果为

Sub Main()
Dim n As Double
Dim j as integer
Console.WriteLine("Enter a starting number.")
n = Console.ReadLine()
j = 0

Do While n <> 1

    Do While n > 1
        'Every Time i enter in the cicle, the "operation counter" increses by one
        j = j + 1

        If n Mod 2 = 0 Then
            n = n / 2
        Else
            n = (n * 3) + 1

        End If
        Console.WriteLine(n)
    Loop
    If n = 1 Then
        Console.WriteLine(
        n = Console.ReadLine()
    End If

Loop

Console.WriteLine("I make " & j & " operations to get here!")
Console.ReadLine()

End Sub

【讨论】:

    【解决方案2】:
        Sub Main()
            Dim n As Double
            Console.Write("Enter a starting number: ")
            n = Convert.ToDouble(Console.ReadLine())
            Console.WriteLine()
    
            Dim loopsCounter As Integer = 0
    
            Do While n > 0
                Do While n > 1
                    loopsCounter += 1
    
                    If n Mod 2 = 0 Then
                        n = n / 2
                    Else
                        n = (n * 3) + 1
                    End If
    
                    Console.WriteLine(n)
                Loop
    
                Console.WriteLine()
                Console.WriteLine(String.Format("{0} loops to result.", loopsCounter))
    
                If n = 1 Then
                    Console.WriteLine()
                    Console.Write("Enter another number: ")
                    n = Convert.ToDouble(Console.ReadLine())
                    loopsCounter = 0
                End If
            Loop
    
            Console.ReadLine()
        End Sub
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多