在Go语言中,有一种标准类型可以进行“精确除法”吗?

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

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

huangapple
  • 本文由 发表于 2023年3月29日 00:57:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/75869031.html
匿名

发表评论

匿名网友

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

确定