回答

收藏

在 Go 中找到两个整数之间的最小值的正确方法是什么?

技术问答 技术问答 663 人阅读 | 0 人回复 | 2023-09-11

我在我的程序中导入了数学库,我试图在三个数字中找到最小值:3 w0 H& J  y: d5 S9 m
v1[j 1] = math.Min(v1[j] 1,math.Min(v0[j 1] 1,v0[j] cost))其中 v1 声明为:
) }' e! _' Z% P* V9 u* M$ T) Z
    t := "stackoverflow"v1 := make([]int,len(t) 1)
    ; E0 ]" K3 A% u) m8 ?" ^) v
但是,当我操作我的程序时,有以下错误:
+ R3 Y' S) \- ~/ {
    ./levenshtein_distance.go:36: cannot use int(v0[j  1]  1(type int) as type float64 in argument to math.Min+ ?# K/ H9 k0 r! V9 ~
我觉得很奇怪,因为我有另一个程序可以写
8 @. M( F: V  X; @$ M3 vfmt.Println(math.Min(2,3))程序输出2没有抱怨。
3 y+ \- C7 d' A- @1 D! Y# ~所以我最终把值变成了 float64,这样就math.Min可以了:+ P, N: e$ p; T# X
    v1[j 1] = math.Min(float64(v1[j] 1),math.Min(float64(v0[j 1] 1),float64(v0[j] cost)))
    + S3 s5 Y7 u& i0 r% p+ b6 v
用这种方法,我收到了以下错误:
6 N" b/ o" b7 p7 G6 i# [
    ./levenshtein_distance.go:36: cannot use math.Min(int(v1[j]   1),math.Min(int(v0[j  int(v0[j]   cost))) (type float64) as type int in assignment
    0 l2 {2 h+ @$ L- A/ d
所以为了摆脱这个问题,我只是把结果投回 int
* U" f3 z& L- U5 i3 l我觉得很低效,很难阅读:
; {) t( _3 L% K" }( q8 y
    v1[j 1] = int(math.Min(float64(v1[j] 1),math.Min(float64(v0[j 1] 1),float64(v0[j] cost))))9 Z& G0 c2 V, Z' s/ i: K, B
我还写了一个小的minInt函数,但我认为这应该是不必要的,因为其他程序math.Min工作可以很好地利用整数,所以我得出结论,这一定是我的程序问题,而不是库本身。
8 X. w& D! ~! R  i5 [, u我做错了什么吗?
9 c! {- Q$ i8 Q4 J/ Q这是一个可以重现上述问题的程序,特别是第 36 线:package main
3 h1 F5 {+ W% ]2 N) h7 D[code]import  "math")func main()      LevenshteinDistance("stackoverflow","stackexchange")}func LevenshteinDistance(s string,t string) int    if s == t        return    if len(s) == 0        return len(t)   }    if len(t) == 0        return len(s)   }    v0 := make([]int,len(t) 1)    v1 := make([]int,len(t) 1)    for i := 0; i 不,我觉得写这样的东西很好:例如,stdlib 的 sort.go在文件顶部附近执行:
3 m" O2 X5 h9 i) a' v[code]func min(a,b int) int    if a math.Min(2,3)碰巧起作用,因为Go 中的数字常量是无类型的。但是,请注意 float64s 被视为通用数字类型,因为如果转换为 float64,以上整数2^五三四舍五入。
+ A6 V3 g/ H- e' M尽管在当我写这篇文章的时候不适用于稳定 Go,但在Go 1.18 beta 中,您可以编写一个通用min运行时,函数与手动编码的单一版本一样高效。6 {  T* y. N9 i7 F- a5 R
一直在讨论更新 stdlib 添加现有函数的通用版本,但如果发生这种情况,等待更高的版本。
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则