Visual Basic - 1-100,数字可被2和3整除

时间:2014-01-21 11:34:54

标签: vb.net loops integer

控制台似乎继续打印重复的值'1' 也许这是因为我没有在循环中正确递增值? 或者我在不正确的位置声明变量的值

Dim divx As Integer
    Dim divy As Integer

    divx = 1

    Do While divx < 100

        divy = divx Mod 2

        If Not (divy = 0) Then
            Console.WriteLine(divx)
        Else
            divx += 1
        End If

    Loop

3 个答案:

答案 0 :(得分:2)

是的,你没有增加它,你可以省略Else

Do While divx < 100
    divy = divx Mod 2

    If Not (divy = 0) Then
        Console.WriteLine(divx)
    End If
    divx += 1
Loop

但是如果你还想显示可以被3整除的数字,你可以用这种方式修改你的循环:

Dim divx As Integer = 1
Do While divx < 100
    Dim isDivisableBy2Or3 = divx Mod 2 = 0 OrElse divx Mod 3 = 0
    If isDivisableBy2Or3 Then
        Console.WriteLine(divx)
    End If
    divx += 1
Loop

答案 1 :(得分:0)

Do While divx < 100

    If Not (divx Mod 2 = 0) Then
        Console.WriteLine("Divisible by 2: " & divx)
    End If

    If Not (divx Mod 3 = 0) Then
        Console.WriteLine("Divisible by 3: " & divx)
    End If

    divx += 1

Loop

答案 2 :(得分:0)

如果您的目标只是列出可被2和3整除的数字,那么这应该是最短的路线。只是试图帮助:)如果2或3然后改变和Or。

 For x As Integer = 1 To 100
    If (x Mod 2 = 0) And (x Mod 3 = 0) Then Console.WriteLine(x)
 Next x

如果条件是2和3而不是5则那么......

 For x As Integer = 1 To 100
    If (x Mod 2 = 0) And (x Mod 3 = 0) And Not (x Mod 5 = 0) Then Console.WriteLine(x)
 Next x