在Go语言中,x%y表示取x除以y的余数。

huangapple go评论94阅读模式
英文:

What kind of operation is x%y in golang?

问题

我正在通过一些 Golang 教程,我遇到了这个 for 循环:

for n := 0; n <= 5; n++ {
    if n%2 == 0 {
        continue
    }
    fmt.Println(n)
}

我对 n%2 这个语句感到困惑。

这段代码的输出是:

1
3
5

看起来这些数字不是 2 的倍数,但如果是这样的话,我不明白 == 0 这部分的含义是什么?是否有关于这个操作的资源,或者我应该查找一些内容?

英文:

I'm going through some golang tutorials, and I came across this for loop:

for n := 0; n &lt;= 5; n++ {
    if n%2 == 0 {
        continue
    }
    fmt.Println(n)
}

I'm confused by the n%2 statement.

The output of this is:

1
3
5

It looks like these are not multiples of 2, but I'm not understanding the == 0 part of the statement if that's the case? Is there a resource that talks about this operation, or something I should look up?

答案1

得分: 12

这被称为取余运算符,它返回除法运算的余数。因此,当X可以被Y整除时,X % Y == 0将为真。

这个运算符和用%表示它在许多语言中都很常见。

参考相关问题:https://stackoverflow.com/questions/17524673/understanding-the-modulus-operator

英文:

This is called the remainder operator, it returns the remainder of a division operation. Hence X % Y == 0 will be true when X can be evenly divided by Y.

This operator and % to represent it is common in many languages.

See related question: https://stackoverflow.com/questions/17524673/understanding-the-modulus-operator

答案2

得分: 2

这是余数/模运算符。它返回给定数字除法的余数:
https://en.wikipedia.org/wiki/Modulo_operation

这段代码计算所有的奇数。

英文:

It's the remainder/modulo-operator. This returns the rest of the division with the given number:
https://en.wikipedia.org/wiki/Modulo_operation

This code fragment calculates all uneven numbers.

huangapple
  • 本文由 发表于 2017年8月29日 02:37:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/45925388.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定