gpt4 book ai didi

c - 对与c中的字符串数组相关的数组进行排序

转载 作者:行者123 更新时间:2023-11-30 15:09:02 25 4
gpt4 key购买 nike

我试图根据数组的值对与数组相关的字符串进行排序,由于某种原因,排序部分开始工作..当我尝试对彼此相关的元素进行排序并出于某种原因打印它们时打印结果非常随机

#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++;
}
}

谢谢!

最佳答案

我认为您应用的排序在排序函数的第一个条件上似乎是错误的

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

假设当 i 等于 size 时,平均值 [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

关于c - 对与c中的字符串数组相关的数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36917960/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com