golang what is the right way to use math.max on two uint values?

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

golang what is the right way to use math.max on two uint values?

问题

这是我所做的事情,非常丑陋。

如何正确使用math.Max来比较两个无符号整数(uint)?

vs.curView.Viewnum = uint(math.Max(float64(args.Viewnum+1), float64(vs.curView.Viewnum)))
英文:

This is what I do, it is extremely ugly.

What is the right way to use math.Max for 2 uint s?

vs.curView.Viewnum =uint(math.Max(float64(args.Viewnum+1), float64(vs.curView.Viewnum)))

答案1

得分: 12

math.Max存在的主要原因是确保正确处理IEEE浮点数的一些特殊情况(正无穷大、负无穷大、NaN和有符号零)。

对于简单的整数来说,这些问题并不相关,所以你可以直接使用明显的实现。例如:

if args.Viewnum+1 > vs.curView.Viewnum {
    vs.curView.Viewnum = args.Viewnum+1
}
英文:

The main reason math.Max exists is to ensure some of the special cases of IEEE floating point are handled correctly (positive and negative infinity, NaN and signed zeroes).

These issues are not relevant for simple integers, so you may as well just use the obvious implementation. Something like:

if args.Viewnum+1 > vs.curView.Viewnum {
    vs.curView.Viewnum = args.Viewnum+1
}

答案2

得分: 0

尽管这个问题很旧,但也许这个包可以节省某人的时间和精力。它可以通过go get命令获取,并像往常一样通过URL导入。

用法:

import (
    "fmt"
    "<完整的URL>/go-imath/ix" // 用于int类型的函数
)
...
fmt.Println(ix.Max(100, 152)) // 输出: 152
fmt.Println(ix.Maxs(234, 55, 180)) // 输出: 234
fmt.Println(ix.MaxSlice([]int{2, 29, 8, -1})) // 输出: 29
英文:

Though the question is old, maybe this package will save someone's time and efforts. It is obtainable via go get and importing by URL, as usual.

Usage:

import (
    &quot;fmt&quot;
    &quot;&lt;Full URL&gt;/go-imath/ix&quot; // Functions for int type
)
...
fmt.Println(ix.Max(100, 152)) // Output: 152
fmt.Println(ix.Maxs(234, 55, 180)) // Output: 234
fmt.Println(ix.MaxSlice([]int{2, 29, 8, -1})) // Output: 29

huangapple
  • 本文由 发表于 2015年1月29日 12:37:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/28207090.html
匿名

发表评论

匿名网友

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

确定