加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 查找数组中的最大和最小数字

发布时间:2020-12-16 10:40:39 所属栏目:百科 来源:网络整理
导读:考虑: #include iostream // Include header fileusing namespace std;int main () //start of main function{ int values[20]; // Declares array and how many elements int small,big; // Declares integer big = small = values[0]; // Assigns element
考虑:

#include <iostream> // Include header file

using namespace std;

int main () //start of main function
{

    int values[20]; // Declares array and how many elements
    int small,big; // Declares integer
    big = small = values[0]; // Assigns element to be highest or lowest value

    for (int i = 0; i < 20; i++) // Counts to 20 and prompts the user for a value and stores it
    {
        cout << "Enter value " << i << ": ";
        cin >> values[i];
    }

    for (int i = 0; i < 20; i++) // Works out the biggest number
    {
        if(values[i] > big) // Compare biggest value with current element
        {
            big = values[i];
        }
    }

    for (int i = 0; i < 20; i++) // Works out the smallest number
    {
        if (values[i] < small) // Compares smallest value with current element
        {
            small = values[i];
        }
    }

    cout << "The biggest number is " << big << endl; // Prints outs the biggest number
    cout << "The smallest number is " << small << endl; // Prints out the smallest number
}

到目前为止这是我的代码.我遇到的问题是它打印出最大数量的数组.将第一个元素分配给最高和最低值的方法.如果我单独使用它,它可以工作.有什么建议?

解决方法

除非你真的必须实现自己的解决方案,否则可以使用 std::minmax_element.这将返回一对迭代器,一个到最小元素,一个到最大元素.

#include <algorithm>

auto minmax = std::minmax_element(std::begin(values),std::end(values));

std::cout << "min element " << *(minmax.first) << "n";
std::cout << "max element " << *(minmax.second) << "n";

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读