C找到最小的3个数字
发布时间:2020-12-16 03:15:32 所属栏目:百科 来源:网络整理
导读:参见英文答案 Simple logic problem: Finding largest and smallest number among 3 numbers5个 有什么办法使这个功能更加优雅吗?我是C的新手,我不知道是否有更标准化的方法来做到这一点.这可以变成一个循环,所以变量的数量不受我的代码的限制吗? float sm
参见英文答案 >
Simple logic problem: Finding largest and smallest number among 3 numbers5个
有什么办法使这个功能更加优雅吗?我是C的新手,我不知道是否有更标准化的方法来做到这一点.这可以变成一个循环,所以变量的数量不受我的代码的限制吗? 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; } 解决方法
可以做出许多改进.
您可以使用标准功能使其更清晰: // Notice I made the return type an int instead of a float,// since you're passing in ints int smallest(int x,int z){ return std::min(std::min(x,y),z); } 或者更好的是,正如在评论中指出的那样: int smallest(int x,int z){ return std::min({x,y,z}); } 如果你希望它可以在任何数量的int上运行,你可以这样做: 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; } 你也可以使它通用,以便它可以在任何类型上运行,而不是只是int 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; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |