查找在列C的最高数量++ [英] Finding the highest number in an array C++
问题描述
因此,这里是什么我试图做的事 - 编写一个程序,用50个值获得数组中的最高数,打印出来的数组。虽然我已经撞南墙。我是pretty肯定,我已经得到了非常困惑,在函数中返回,例如为什么指数未定义出了在findSmall和findBig功能循环?
So here is what I am trying to do - To write a program with an array of 50 values getting the highest number in the array and printing it out. I have hit a brick wall though. I am pretty sure I've gotten very confused with the returning in the function, for example why is index "undefined" out of the for loop in the findSmall and findBig functions?
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int findSmallest(int array[], int size, int index)
{
int index_of_smallest_value = index;
for (int i = index + 1; i < size; i++)
{
if (array[i] < array[index_of_smallest_value])
{
index_of_smallest_value = i;
}
}
return index_of_smallest_value;
}
int findBiggest(int array[], int size, int index)
{
int index_of_biggest_value = index;
for (int i = index + 1; i < size; i++)
{
if (array[i] > array[index_of_biggest_value])
{
index_of_biggest_value = i;
}
}
return index_of_biggest_value;
}
int findSmall(int array[], int size)
{
int index = 0;
for (int i = 0; i < size; i++)
{
index = findSmallest(array, size, i);
//cout << index << endl;
}
return index;
}
int findBig(int array[], int size)
{
int index = 0;
for (int i = 0; i < size; i++)
{
index = findBiggest(array, size, i);
//cout << index << endl;
}
return index;
}
int main()
{
int array[50];
srand(time(NULL));
for (int i = 0; i < 50; i++)
array[i] = rand() % 100;
cout << "The smallest digit is " << findSmall(array, 50) << endl;
cout << "The biggest digit is " << findBig(array, 50);
cin.get();
}
我已经编辑我的上述code,但是我不断收到来自findSmall和findBig函数返回49。
I've edited my above code, however I keep getting returned 49 from both findSmall and findBig functions.
推荐答案
您可以做到这一点的C ++ / STL的方式。这不仅使用数组,而且与其他STL容器。
You can do it the C++/STL way. This does not only work with arrays, but also with other STL containers.
#include <iterator>
#include <algorithm>
int minelem = *std::min_element(begin(array), end(array));
int maxelem = *std::max_element(begin(array), end(array));
这code遍历数组的两倍。出于性能的考虑,你可能会考虑合并循环。或C ++ 11你甚至可以
This code loops over array twice. For performance reasons you might consider merging the loops. Or in C++11 you could even
auto result = std::minmax_element(begin(array), end(array));
这篇关于查找在列C的最高数量++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!