微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

C找到最小的3个数字

参见英文答案 > 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;
}

原文地址:https://www.jb51.cc/c/112060.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐