dongxia19772008 2019-01-16 03:17
浏览 19
已采纳

为什么Go的结果相同?

When i review a Golang project, i found some code like this, now is Unix timestap. Call this function once every second:

//main.go
func PrevSlot(now int64) int64 {
    // now = time.Now().Unix()
    var blockInterval = int64(10)

    result := int64((now-1)/blockInterval) * blockInterval // why result is same ?
    plog.Println("PrevSlot:", int64(result), int64((now-1)/blockInterval), now)
    return result
}


func main() {
    ticker := time.NewTicker(1 * time.Second)
    for {
        <-ticker.C

        now := time.Now().Unix()
        PrevSlot(now)
    }

}

Output:

2019-01-16 10:58:31.668597 I | dpos.go: PrevSlot: 1547607510 154760751 1547607511
2019-01-16 10:58:32.668649 I | dpos.go: PrevSlot: 1547607510 154760751 1547607512
2019-01-16 10:58:33.668568 I | dpos.go: PrevSlot: 1547607510 154760751 1547607513
2019-01-16 10:58:34.668572 I | dpos.go: PrevSlot: 1547607510 154760751 1547607514
2019-01-16 10:58:35.668547 I | dpos.go: PrevSlot: 1547607510 154760751 1547607515

The result is same. Why is this, what is the principle?

  • 写回答

2条回答 默认 最新

  • dongwei4103 2019-01-16 03:30
    关注

    Actually,

    int64((now - 1)/blockInterval * blockInterval
    

    does not return the same result all the time. You will notice it changing every 10 seconds.

    This is caused by integer division in Go. If you apply integer division to any two numbers, then the fractional part of the result (remainder) is dropped. For example, int(12 / 10) = 1. In your specific case - dividing by ten, the code will drop the remainders from 1 until 9, and only increment the value when you get to the next 10.

    If you'd like to increase the precision of your operations, then you can force floating point division like so float64(12)/float64(10).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作