【发布时间】:2015-03-02 18:16:43
【问题描述】:
#include <iostream>
#include <cstdlib>
#include <ctime>
#include<algorithm>
using namespace std;
bool findNthMax(double arr[], int len, int n, double& nth_max)
{
sort(arr, arr+n);
//Counter
int c = 1;
//Initialize nth max
nth_max = arr[0];
//Loop in the array while the count is less than (n)
for (int i = 0; i < len && c < n; i++)
{
if (arr[i] != nth_max)
c++;
nth_max = arr[i];
}
return nth_max;
}
int main()
{
int n;
double arr[10];
double y;
cout << "The random array elements are:" << endl;
srand((unsigned)time(0));
for(int i=0; i<10; i++){
arr[i] = (rand()%100);
cout << arr[i] << ' ' ;
}
cout << endl;
cout << "Input a positive integer n: " ;
cin >> n ;
if(n>10)
cout << "The nth largest value does not exist." << endl;
else
cout << "The nth largest value is: " << findNthMax(arr, 10, n, y) << endl;
return 0;
}
编辑:如果第 n 个最大值不存在,该函数返回 false;第一个参数是输入数组;第二个参数是数组大小;第三个参数用于将 n 的值传递给函数;最后 参数是找到的第 n 个最大值。
主函数生成一个包含 10 个双随机元素的数组(在 [0, 99] 范围内。它打印出这 10 个元素。提示用户输入 正整数 n,然后打印出第 n 个最大值 数组。
我的输出如何显示第 n 大:当 n = 2 时为 1
【问题讨论】:
-
你为什么返回 bool?
-
不太清楚你在做什么。但是如果你传递长度为 n 的数组,那么应该总是有 m=n “最大”值。如果给出的数字大于元素的数量,则可以返回 false。对于其他情况,只需对数组进行排序并返回索引值我的值 m(m 最大)。
-
您打印的是布尔返回值,而不是结果(写给
y会让人困惑,而返回值毫无意义,当然与描述不符)。我认为您想对整个数组进行排序,而不仅仅是第一个n元素,并且可能以相反的顺序。通常,您希望在调试器中单步执行代码,以查看它实际在做什么,以及它与您希望它做什么有什么不同。 -
首先为什么你的函数的返回类型是bool。其次,为什么您只对数组的前 n 个元素进行排序?最后,循环做什么?