C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了C找到最小的3个数字大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
参见英文答案 > @L_772_0@5个
有什么办法使这个功能更加优雅吗?我是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;
}

解决方法

@H_502_8@ 可以做出许多改进. @H_197_8@您可以使用标准功能使其更清晰:

// 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);
}
@H_197_8@或者更好的是,正如在评论中指出的那样:

int smallest(int x,int z){
    return std::min({x,y,z});
}
@H_197_8@如果你希望它可以在任何数量的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;
}
@H_197_8@你也可以使它通用,以便它可以在任何类型上运行,而不是只是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;
}

大佬总结

以上是大佬教程为你收集整理的C找到最小的3个数字全部内容,希望文章能够帮你解决C找到最小的3个数字所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。