In the language there is a minimum function https://golang.org/pkg/math/#Min But what if I have more than 2 numbers? I must to write a manual comparison in a for loop, or is there another way? The numbers are in the slice.
2条回答 默认 最新
- duanmaifu3428 2017-07-06 06:07关注
No, there isn't any better way than looping. Not only is it cleaner than any other approach, it's also the fastest.
values := []int{4, 20, 0, -11, -10} min := values[0] for _, v := range values { if (v < min) { min = v } } fmt.Println(min)
EDIT
Since there has been some discussion in the comments about error handling and how to handle empty slices, here is a basic function that determines the minimum value. Remember to import
errors
.func Min(values []int) (min int, e error) { if len(values) == 0 { return 0, errors.New("Cannot detect a minimum value in an empty slice") } min = values[0] for _, v := range values { if (v < min) { min = v } } return min, nil }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥20 基于MATLAB的TDOA
- ¥15 为啥输入字体突然变了
- ¥20 已知坐标,换成MATLAB可以用的数据
- ¥15 这个python五子棋代码的每一句意思是什么啊
- ¥15 求一段隐藏代码,隐藏一些内容
- ¥15 汇川EASY521plc电子凸轮
- ¥15 C++ 如何判断设置快捷键来实现隐藏/显示窗口
- ¥15 关于#材料工程#的问题:有没有具有电子阻挡层和空穴阻挡层的电池仿真silvaco代码例子或者其他器件具有阻挡层例子的silvaco代码(最好还有相关文献)
- ¥60 基于MATLAB的TAOD算法
- ¥15 Groimp使用疑问