2013-05-27 80 views
2

我有5個學生的名字及其3個科目的成績,我計算了他們的3個課程的平均值。但是之後我需要將他們的數據(名稱,3門課程和平均成績)從最高平均分到最低平均分。 任何人都可以告訴我我的代碼有什麼問題嗎? 這裏是我的代碼...如何在C++中對二維數組進行排序

# include <iostream> 
# include <string> 
# include <iomanip> 
using namespace std; 
void read(string names[],double grades[][4],int n); 
void average(double grades[][4], int n); 
void sort(string names[],double grades[][4], int n); 
int main() 
{ 
    string names[5]; double grades[5][4]; 
    cout<<fixed<<showpoint<<setprecision (2); 
    cout<<" please enter the names and grades(math,phy,cpp) for 5 students\n"; 
    read(names,grades,5); 
    average(grades,5); 
    sort(names,grades,5); 
    for(int rows=0; rows<5; rows++) 
    { 
     cout<<names[rows]<<"\t"; 
     for(int col=0; col<4; col++) 
     { 
      cout<<grades[rows][col]<<"\t"; 
     } 
     cout<<endl; 
    } 







    system("pause"); 
    return 0; 
} 
void read(string names[],double grades[][4],int n) 
{ 
    for(int rows=0; rows<n; rows++) 
    { 
      cin>>names[rows]; 
     for(int col=0; col<3; col++) 
     { 
      cin>>grades[rows][col]; 
     } 
    } 
    system("cls"); 
} 
void average(double grades[][4], int n) 
{ 
    double sum; 
    for(int rows=0; rows<n; rows++) 
    { 
     sum=0.0; 
     for(int col=0; col<3;col++) 
     { 
      sum=sum+grades[rows][col]; 
     } 
     grades[rows][3]=sum/3; 
    } 
} 

void sort(string names[],double grades[][4], int n) 
{ 
    double temp;int end=n;string swap_names; 


    for(int rows=0; rows<end; rows++) 
    { 
     if(grades[rows][3]> grades[rows+1][3]) 
     { 
      for(int col=0; col<4;col++) 
      { 
       temp=grades[rows+1][col]; 
       grades[rows+1][col]=grades[rows][col]; 
       grades[rows][col]=temp; 
      } 
      swap_names=names[rows+1]; 
      names[rows+1]=names[rows]; 
      names[rows]=swap_names; 
     } 
    } 


} 

謝謝。

+0

一個建議:包含自己的姓名,年級,平均學生創建一個類。然後將這些對象存儲在一個向量中。然後對自定義函數或可調用對象使用'std :: sort()'。 – trojanfoe

+5

歡迎來到Stack Overflow!要求人們發現代碼中的錯誤並不是特別有效。您應該使用調試器(或者添加打印語句)來分析問題,追蹤程序的進度,並將其與預期發生的情況進行比較。只要兩者發生分歧,那麼你就發現了你的問題。 (然後如果有必要,你應該構建一個[最小測試用例](http://sscce.org)。) –

回答

0

問題出在您的sort()函數。泡沫排序是O(n )排序,其中您的sort()只需要O(n)時間是正確的。

嘗試的sort()這個修正碼,

void sort(string names[],double grades[][4], int n) 
{ 
    double temp; 
    int end=n; 
    string swap_names; 
    for(int rows1=0; rows1<end; rows1++) 
    { 

     for(int rows2=0; rows2<end; rows2++) 
     { 
     if(grades[rows1][3] < grades[rows2][3]) 
     { 
      for(int i=0; i<4; i++) 
      { 
       temp=grades[rows1][i]; 
       grades[rows1][i]=grades[rows2][i]; 
       grades[rows2][i]=temp; 
      } 
      swap_names=names[rows1]; 
      names[rows1]=names[rows2]; 
      names[rows2]=swap_names; 
     } 
     } 
    } 
} 
+0

謝謝...我感謝你的幫助。有效。 – lwe

0

您的排序算法尚未完成。這是所謂的Bubble排序算法的一次迭代,更多詳細信息請參見Bubble sort。然而,如果你的數據庫很大,那麼泡泡排序會有相當不好的表現,那麼你應該真的考慮按照其中一條評論的建議,使用庫中的排序。

相關問題