2015-03-02 143 views
0
#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個最大值。排列中第k個最大元素

主函數生成一個包含10個雙隨機元素的數組(在[0,99]範圍內),輸出這10個元素,提示用戶輸入一個 正整數n,然後輸出第n個最大值。在 陣列

我的輸出如何以往顯示第n個最大的:1,當n = 2

+0

爲什麼要退布爾? – 0x499602D2 2015-03-02 18:19:20

+0

不太清楚你在做什麼。但是如果你傳遞長度爲n的數組,那麼應該總是達到m = n「最大」的值。如果數量大於元素數量,則可以返回false。對於其他情況,只需對數組進行排序並返回索引值m(m-最大)的值。 – matthias 2015-03-02 18:22:05

+2

您正在打印布爾返回值,而不是結果(將其容易混淆地寫入'y',而返回值沒有意義,當然與描述不符)。我想你想排序整個數組,而不僅僅是第一個'n'元素,並且可能以相反的順序。一般來說,您希望在調試器中逐步查看代碼,看看它實際上在做什麼,以及與您希望執行的操作有什麼不同。 – 2015-03-02 18:26:51

回答

1

if arr[1] != nth_max後遞增c 2這意味着c !< n,所以你for循環退出後2環通過。

您需要對整個數組進行排序,b/c缺少在第二個最大值之前可能有8個副本的情況,例如{8,8,8,8,8,8,8,8,8,1 ,2,8,8,8}。

sort(arr, arr+len); 

您應該在數組的末尾開始你for環......

nth_max = arr[len-1];  
for (int i = len-1; i >= 0 && c < n; i--) 

然後還輸出變量y之前運行的功能:

findNthMax(arr, 10, n, y); 
cout << "The nth largest value is: " << y << endl; 
+0

這幾乎是實際的工作,但就像你說我有數組排序問題。 – friedrojak 2015-03-02 19:28:33

+0

@friedrojak排序呼叫已添加到答案。你幾乎擁有它。 – TriHard8 2015-03-02 20:28:08

相關問題