在C ++中找到3个数字中的最小数字

编程入门 行业动态 更新时间:2024-10-10 03:29:11
本文介绍了在C ++中找到3个数字中的最小数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

有什么方法可以使此功能更优雅?我是C ++的新手,我不知道是否有更标准化的方法来执行此操作.可以把它变成一个循环,这样变量的数量就不会像我的代码那样受到限制吗?

Is there any way to make this function more elegant? I'm new to C++, I don't know if there is a more standardized way to do this. Can this be turned into a loop so the number of variables isn't restricted as with my code?

float smallest(int x, int y, int z) { int smallest = 99999; if (x < smallest) smallest=x; if (y < smallest) smallest=y; if(z < smallest) smallest=z; return smallest; }

推荐答案

可以进行许多改进.

您可以使用标准功能使其更清晰:

You could use standard functions to make it clearer:

// Notice I made the return type an int instead of a float, // since you're passing in ints int smallest(int x, int y, int z){ return std::min(std::min(x, y), z); }

或者如评论中所指出的那样更好:

Or better still, as pointed out in the comments:

int smallest(int x, int y, int z){ return std::min({x, y, z}); }

如果您希望它可以在任意数量的int上运行,则可以执行以下操作:

If you want it to operate on any number of ints, you could do something like this:

int smallest(const std::vector<int>& intvec){ int smallest = std::numeric_limits<int>::max(); // Largest possible integer // there are a number of ways to structure this loop, this is just one for (int i = 0; i < intvec.size(); ++i) { smallest = std::min(smallest, intvec[i]); } return smallest; }

您还可以使其通用,使其可以在任何类型上运行,而不仅仅是ints

You could also make it generic so that it'll operate on any type, instead of just ints

template <typename T> T smallest(const std::vector<T>& vec){ T smallest = std::numeric_limits<T>::max(); // Largest possible integer // there are a number of ways to structure this loop, this is just one for (int i = 0; i < vec.size(); ++i) { smallest = std::min(smallest, vec[i]); } return smallest; }

更多推荐

在C ++中找到3个数字中的最小数字

本文发布于:2023-11-29 10:05:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646093.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数字   最小   中找到

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!