英文:
Is there a standard type to do "accurate division" in Go?
问题
我想在Go语言中进行一些"精确除法"操作。是否有标准类型可以实现这个功能?
例如,我想存储值"1/3"和"2/3",并且能够对它们进行加法运算。
我可以像这样定义自己的类型:
type MyType struct {
Numerator int
Denominator int
}
并定义如下函数:
func (a MyType) Plus(b MyType) MyType {
d := a.Denominator * b.Denominator
n := (a.Numerator * b.Denominator) + (b.Numerator * a.Denominator)
return MyType{Numerator: n, Denominator: d}
}
但可能有更优雅的方法来实现这个功能,或者已经有一个"标准类型"可以实现这个功能。
英文:
I would like to do some "accurate division" in go. Is there a standard type for that?
For example, I would like to store the value "1/3" and "2/3" and be able to add them.
I can define my own type like this:
type MyType struct {
Numerator int
Denominator int
}
and define functions like:
func (a MyType) Plus(b MyType) MyType {
d := a.Denominator * b.Denominator
n := (a.Numerator * b.Denominator) + (b.Numerator * a.Denominator)
return MyType{Numerator: n, Denominator: d}
}
but there is probably a more elegant way to do this or a "standard type" that already does that.
答案1
得分: 0
我不知道 big.Rat
。这就是我需要的!谢谢你的帮助。
英文:
I didn't know about big.Rat
. This is all I need! Thank you for your help
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论