找到一个数组的最大和最小数

编程入门 行业动态 更新时间:2024-10-11 19:17:52
本文介绍了找到一个数组的最大和最小数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 #include <iostream> //include header file using namespace std; int main () //start of main fcn { int values[ 20 ]; //delcares 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 user for value and stores it { cout << "Enter value " << i << ": "; cin >> values[i]; } for (int i = 0; i < 20; i++) //works out bigggest number { if(values[i]>big) //compare biggest value with current element { big=values[i]; } } for (int i = 0; i < 20; i++) //works out smallest number { if(values[i]<small) //compares smallest value with current element { small=values[i]; } } cout << "The biggest number is " << big << endl; //prints outs biggest no cout << "The smallest number is " << small << endl; //prints out smalles no }

这是我的code到目前为止,我遇到的问题是它打印出数组的最大数量。是与分配给最高值和最低值的第一个元素。它的工作原理,如果我做他们分开。有什么建议?

This is my code so far the problem I am having is with it printing out the biggest number of the array. Something to do with assigning the first element to the highest and lowest value. It works if I do them seperately. Any suggestions?

推荐答案

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

Unless you really must implement your own solution, you can use std::minmax_element. This returns a pair of iterators, one to the smallest element and one to the largest.

#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";

更多推荐

找到一个数组的最大和最小数

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

发布评论

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

>www.elefans.com

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