阅读文档- http://golang.org/pkg/math/big/
Mod将z设为y != 0的模x%y,并返回z。如果y == 0,则会发生除以零的运行时恐慌。国防部实现欧几里德模数(不像Go);更多细节请参见DivMod。
10%4 =2,但我用这个得到8(使用数学/大包来做同样的事情)- 86etDvLYq
package main
import "fmt"
import "math/big"
import "strconv"
func main() {
ten := new(big.Int)
ten.SetBytes([]byte(strconv.Itoa(10)))
four := new(big.Int)
four.SetBytes([]byte(strconv.Itoa(4)))
tenmodfour := new(big.Int)
tenmodfour = tenmodfour.Mod(ten, four)
fmt.Println("mod", tenmodfour)
}我很可能出了什么问题。哪里弄错了?
发布于 2014-06-07 16:05:25
这是因为SetBytes没有按照你的想法去做!使用SetInt64代替。
ten := new(big.Int)
ten.SetBytes([]byte(strconv.Itoa(10)))
four := new(big.Int)
four.SetBytes([]byte(strconv.Itoa(4)))
fmt.Println(ten, four)结果:
12592 52事实上,12592%52 == 8
如果您想使用大于int64允许您操作的数字,也可以使用SetString函数:
n := new(big.Int)
n.SetString("456135478645413786350", 10)发布于 2014-06-07 18:52:05
除了julienc的答案之外,如果要使用SetBytes,就必须将数字转换为像this这样的字节:
func int2bytes(num int) (b []byte) {
b = make([]byte, 4)
binary.BigEndian.PutUint32(b, uint32(num))
return
}
func main() {
ten := new(big.Int)
ten.SetBytes(int2bytes(10))
four := new(big.Int)
four.SetBytes(int2bytes(4))
fmt.Println(ten, four)
tenmodfour := new(big.Int)
tenmodfour = tenmodfour.Mod(ten, four)
fmt.Println("mod", tenmodfour)
}https://stackoverflow.com/questions/24098959
复制相似问题