如果我例如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;
}
最初我該如何分配runners_up? – LogicianUnix
最初亞軍與smallest_num相同。 –
或者你可以用INT_MAX初始化runners_up。 –