2014-04-09 62 views
1

如果我例如5 4 3 2 1它給1和2是正確的,但進入,如果我進入1 2 3 4 5它給1和5這是假的....怎麼解決這個問題?如何找到第二個最小的元素

該程序發現通過輸入最小和第二小的元件。

#include<iostream> 
/*This program finds the smallest and second smallest elements through input*/ 
using namespace std; 
/*This program finds the smallest and second smallest elements through input*/ 

int main(){ 
    float input_from_user=0.0, largest=0.0, smallest_num=0.0, runners_up=0.0; 
    int count, i; 

    cout<<"how many swimming records?"<<endl; 
    cin>>count; 
    cout<<"enter time: "; 
    cin>>input_from_user; 
    smallest_num=input_from_user; 
    largest=input_from_user; 
    for (i=1;i<=count;i++){ 
     cout<<"enter time: "<<endl; 
     cin>>input_from_user; 

     /*Compare smallest number with latest input*/ 
     if (smallest_num>input_from_user){ 
      runners_up=smallest_num; 
      smallest_num=input_from_user; 

     } 


    } 
    cout<<"First:"<<smallest_num<<endl; 
    cout<<"Runners up: "<<runners_up<<endl; 

    return 0; 
} 

回答

2
/*Compare smallest number with latest input*/ 
if (smallest_num>input_from_user){ 
    runners_up=smallest_num; 
    smallest_num=input_from_user; 

} 

上面的代碼看起來問題。

如果input_from_user大於最小num#但小於 runner_up,則應更新runner_up。

/*Compare smallest number with latest input*/ 
if (runner_up > input_from_user){ 
    if(smallest_num > input_from_user) { 
     runners_up=smallest_num; 
     smallest_num=input_from_user; 
    } else runners_up=input_from_user; 

} 
+0

最初我該如何分配runners_up? – LogicianUnix

+0

最初亞軍與smallest_num相同。 –

+0

或者你可以用INT_MAX初始化runners_up。 –

0

最簡單的方式是執行以下步驟:

vector<float> tms; 
for (i=1;i<=count;i++){ 
     cout<<"enter time: "<<endl; 
     cin>>input_from_user; 
     tms.push_back(input_from_user); 
} 
sort(tms.begin(), tms.end()); 

cout<<"First:"<< tms[0] <<endl; 
cout<<"Runners up: "<< tms[1] <<endl; 

此代碼僅訪問元素之前缺少長度一些檢查。

這不是最佳的,因爲它不排序上的所有元素,所以有另一種方法,而不是排序 - 已分類只有有機會成爲最壞的第二小的那些元素使用額外的「設置」。在最好的情況下,它只會採取前兩項,而不會做其他任何事情,在最壞的情況下,它會像以前一樣對所有元素進行排序。

set<float> out; 
out.insert(v[0]); 
out.insert(v[1]); 

for (auto x = v.begin() + 2; x != v.end(); ++x) 
{ 
    auto second = ++out.begin(); 
    if (*x < *second) 
     out.insert(*x); 
} 

auto p = out.begin(); 
cout << "Smallest: " << *p; 
++p; 
cout << " Second: " << *p << endl; 

您可以隨時「正確定義您的算法」,但上述方法開發和調試代碼更快。

+0

你說得對,'std :: sort'比這裏需要的更多的工作。取而代之的是['std :: partial_sort'](http://en.cppreference.com/w/cpp/algorithm/partial_sort)。 – Blastfurnace

相關問題