我想排序基於數組的值的數組的字符串,出於某種原因排序部分工作..當我嘗試排序元素相互關聯並打印出來,出於某種原因打印出來的數字非常隨意排序與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++;
}
}
謝謝!
請不要編寫這樣的代碼。你必須尊重你的同伴,編寫這樣一個不可讀的代碼並不完全是這樣。使用更多的空白空間和更清晰的聲明。 –
'j = i; (i <= size) if((i> = 0) if(gender [i] =='m')':note last last validata index is'i_1' – BLUEPIXY
'while(i <= size) if平均值[i + 1]>平均值[i])':超出界限。 – BLUEPIXY