I am trying to figure out why my sorting code doesn't work. But I just can't understand this code shenanigans. I tried printing every array out but some random number appeared. I don't know anymore. Number I printed was variable j which should go over 20 but somehow printed out 27,28 and it ruined the sorting code, because it worked fine on other projects. Please code god help.you can see i and j printed out followed by numbers in that array, and you can also see the ghost number that came out nowhere(27,28,29).
#include<iostream>
using namespace std;
int main(){
int sc[20], tt, min, max;
while(true){
for(int i=1; i<=20; i++){
cout<<"Student "<<i<<"'s score : ";
cin>>sc[i];
if(sc[i]>40){
cout<<"\nError\n"<<"Try again\n\n";
break;
}
tt=tt+sc[i];
}
break;
}
cout<<"Average = "<<tt/20.0<<endl;
//sorting
for(int i=1; i<=20; i++)
{
for(int j=i+1 ;j<=20; j++)
{
if(sc[i]>sc[j])
{
tt=sc[i];
sc[i]=sc[j];
sc[j]=tt;
}
cout<<i<<" "<<j<<endl<<" "<<sc[i]<<endl<<" "<<sc[j]<<endl<<endl;
}
}
//min max
cout<<"Min = "<<sc[1]<<"\nMax = "<<sc[20];
}
Aucun commentaire:
Enregistrer un commentaire