2016-04-28 48 views
0

我想排序基於數組的值的數組的字符串,出於某種原因排序部分工作..當我嘗試排序元素相互關聯並打印出來,出於某種原因打印出來的數字非常隨意排序與c中的字符串數組有關的數組

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
int sorting(char name[][10],double average[],int size); 

int main() 
{ 
    double sales1[10],sales2[10],sales3[10],average[10],test,totalm=0,totalfm=0,test2;   
int i=0,j; 
char name[10][10],gender[10]; 
printf("Please input the name, the gender, and the sales for the\nfirst three months followed by a spacebar after each element\n"); 
scanf("%s %c %lf %lf %lf",&name[0],&gender[0],&sales1[0],&sales2[0],&sales3[0]); 
average[i]=(sales1[i]+sales2[i]+sales3[i])/3; 
while(strcmp(name[i],"enough")!=0) 
{ 
    i++; 
    printf("Please input the name, the gender, and the sales for the\nfirst three months followed by a spacebar after each element\n"); 
    scanf("%s %c %lf %lf %lf",&name[i],&gender[i],&sales1[i],&sales2[i],&sales3[i]); 
    average[i]=(sales1[i]+sales2[i]+sales3[i])/3; 
} 
sorting(name,average,i); 
j=i; 
while(i>=0) 
{ 
    if(gender[i]=='m') 
     totalm=totalm+average[i]; 
    else 
     totalfm=totalfm+average[i]; 
    i--; 
} 
    while(j>=0) 
    { 
    test2=strcmp(name[j],"enough"); 
    if(test2!=0) 
     printf("%s\t%f\n",name[j],average[j]); 
     j--; 
     } 
     printf("total male sales are %f\n",totalm); 
     printf("total female sales are %f\n",totalfm); 


    } 
int sorting(char name[][10],double average[], int size) 
{ 
int i=0; 
double temp; 
char ntemp[20][20]; 
while(i<=size) 
{ 
    if(average[i+1]>average[i]) 
     { 
      temp=average[i]; 
      strcpy(ntemp[i],name[i]); 
      average[i]=average[i+1]; 
      strcpy(name[i],name[i+1]); 
      average[i+1]=temp; 
      strcpy(name[i+1],ntemp[i]); 
     } 
    i++; 
} 
} 

謝謝!

+2

請不要編寫這樣的代碼。你必須尊重你的同伴,編寫這樣一個不可讀的代碼並不完全是這樣。使用更多的空白空間和更清晰的聲明。 –

+0

'j = i; (i <= size) if((i> = 0) if(gender [i] =='m')':note last last validata index is'i_1' – BLUEPIXY

+0

'while(i <= size) if平均值[i + 1]>平均值[i])':超出界限。 – BLUEPIXY

回答

0

這不是一個有效的排序。您將一個元素泡泡到適當的位置。查找冒泡排序:它有兩個循環。內部循環移動當前元素,外部循環遍歷所有剩餘的未分類元素。

另請參閱您發佈的其他評論以瞭解更多錯誤。

+0

工作很好!謝謝! – Whiteheart

+0

有一件事,即時通訊面臨與女性/男性總的另一個問題...你能看到缺陷嗎? – Whiteheart

1

我想排序您已經應用似乎是錯在你的排序功能的第一個條件

while(i<=size) 
{ 
    if(average[i+1]>average[i]) 
     { 
      temp=average[i]; 

假設條件時,我是等於大小,然後平均[I + 1]將點沒有任何關於你的東西可以說零值,你不設置。 所以試圖糾正這個代碼

for(i=0;i<n;i++) 
    { 
    for(k=0;k<n-i-1;k++) 
    { 
    if(a[k]>a[k+1]) 
     { 
     temp=a[k]; 
     a[k]=a[k+1]; 
     a[k+1]=temp; 
     } 
    } 
    } 

這是冒泡排序,你總是比迭代最後一傳少一個。 更多see here

+0

修正了它!謝謝你的幫助! – Whiteheart