如何在 vb.net 中获得 3 或 5 的倍数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20339043/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 16:00:24  来源:igfitidea点击:

How to get the multiples of 3 or 5 in vb.net?

vb.net

提问by leonardeveloper

How can I get the multiples of 3 or 5 in vb.net? I have this code but it gives me different output. Please help me.

如何在 vb.net 中获得 3 或 5 的倍数?我有这个代码,但它给了我不同的输出。请帮我。

   Dim x As Integer
    For x = 3 To 10
        If x Mod 2 <> 0 Then
            Dim sum As Integer
            sum += x
            MsgBox(x)
        End If
    Next

The output will be 3,5,7,9. The expected output should be 3,5,6,9. So any help?

输出将为3,5,7,9. 预期的输出应该是3,5,6,9。所以有什么帮助吗?

回答by Tim Schmelter

x Mod 2 <> 0gives you all numbers except numbers that are divisible by 2. But you want all numbers that are divisible by 3 or 5.

x Mod 2 <> 0为您提供除可被 2 整除的数字之外的所有数字。但您想要所有可被 3 或 5 整除的数字。

So this gives you the expected output:

因此,这为您提供了预期的输出:

For x = 3 To 9
    If x Mod 3 = 0 OrElse x Mod 5 = 0 Then
    ' ... '

Note that my loops ends with 9 instead of 10 since 10 would be divisible by 5 but you dont expect it.

请注意,我的循环以 9 而不是 10 结束,因为 10 可以被 5 整除,但您不会期望它。

回答by Joel Coehoorn

For Each i As Integer In Enumerable.Range(1,10) _
              .Where(Function(i) i Mod 3 = 0 OrElse i Mod 5 = 0)

    MsgBox(i)
Next i

回答by MarcinJuraszek

Why do you check x Mod 2 <> 0, when you need multiplies of 3 and 5? Try following:

x Mod 2 <> 0当您需要 3 和 5 的乘法时,为什么要检查?尝试以下操作:

Dim x As Integer
For x = 3 To 10
    If x Mod 3 = 0 OrElse x Mod 5 = 0 Then
        Dim sum As Integer
        sum += x
        MsgBox(x)
    End If
Next