gpt4 book ai didi

Swift Double.remainder(dividingBy :) returning negative value

转载 作者:行者123 更新时间:2023-12-05 08:53:50 27 4
gpt4 key购买 nike

let num = 32.0
Double(num).remainder(dividingBy: 12.0)

我得到 -4?..而不是 8.0...它是从 8.0 中减去 12.0

我该如何解决这个问题?

最佳答案

请阅读 documentation小心:

For two finite values x and y, the remainder r of dividing x by y satisfies x == y * q + r, where q is the integer nearest to x / y. If x / y is exactly halfway between two integers, q is chosen to be even. Note that q is not x / y computed in floating-point arithmetic, and that q may not be representable in any available integer type.

(强调我的)

您想使用 truncatingRemainder(dividingBy:)相反:

let num = 32.0
let value = Double(num)
.truncatingRemainder(dividingBy: 12)
print(value) // 8

关于Swift Double.remainder(dividingBy :) returning negative value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52486564/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com