新手求助!一段简单C语言程序!关于sort排序!

DieOrThink 2012-03-19 11:03:42
#include<stdio.h>
#include<algorithm>
#include<string>
using namespace std;
struct node
{
string name[11];
double aver;

};
int cmp(node x,node y)
{
if(x.aver==y.aver)
return x.name>y.name;
else
return x.aver>y.aver;
}
int main()
{
int k,i,j,h,n1,n2;
double sum,m,a[100];
node s[100];
while(scanf("%d",&k)!=EOF)
{
for(h=1;h<=k;h++)
{
scanf("%d",&n1);
for(i=0;i<n1;i++)
scanf("%lf",&a[i]);
scanf("%d",&n2);
for(i=0;i<n2;i++)
{
sum=0;
scanf("%s",&s[i].name);
for(j=0;j<n1;j++)
{
scanf("%lf",&m);
if(m>=60)
sum=sum+a[j]*(m-50)/10;
}
s[i].aver=sum;
}
printf("class %d:\n",h);
sort(s,s+n2,cmp);//问题在这!为什么不能排序!
for(i=0;i<n2;i++)
{
printf("%s %.2lf\n",s[i].name,s[i].aver);
}
printf("\n");
}
}
return 0;
}
...全文
231 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
DieOrThink 2012-03-20
  • 打赏
  • 举报
回复
再次感谢楼上!
x.name > y.name;
就这样直接比较大小?qsort 要用strcmp。
谢谢啦!
hongwenjun 2012-03-20
  • 打赏
  • 举报
回复
sort 是 C++ 泛型 算法库里的
qsort 是 C 标准库里

sort 效率一般被 qsort 高,使用也简单,支持的对象类型也多
C 只能用 qsort 或者 自己实现 sort
DieOrThink 2012-03-20
  • 打赏
  • 举报
回复
谢谢楼上!
但为啥还是不对!我改成qsort排序就对了!?
qsort与sort有啥区别啊?哪个更好用啊?
hongwenjun 2012-03-19
  • 打赏
  • 举报
回复
#include<iostream>
#include<algorithm>
#include<string>
#include<string.h>

using namespace std;

struct node {
string name;
double aver;

};
int cmp(node x, node y)
{
if (x.aver == y.aver)
return x.name > y.name;
else
return x.aver > y.aver;
}


int main()
{
const int size = 5;
node s[size] = {
{"Ajerej", 10.0} , {"Bjerej", 10.0} ,
{"jerej", 55.0} , {"jerej", 1.0} , { "NO_Name", 999}
};

sort(s, s + size, cmp);
for (node* ps = s; ps != s + size ; ++ps) {
cout << ps->aver << " --> " << ps->name << endl;

}
return 0;
}


或者这样 ,楼主的输入控制 看起来真累,好像有问题。
所以直接初始化了
hongwenjun 2012-03-19
  • 打赏
  • 举报
回复
struct node
{
string name[11]; // 这里 好像是 char name[11] 吧
double aver;

};


#include<stdio.h>
#include<algorithm>
#include<string>
#include<string.h>

using namespace std;

struct node {
char name[11];
double aver;

};
int cmp(node x, node y)
{
if (x.aver == y.aver)
return strcmp(x.name , y.name);
else
return x.aver > y.aver;
}


int main()
{
const int size = 5;
node s[size] = {
{"Ajerej", 10.0} , {"Bjerej", 10.0} ,
{"jerej", 55.0} , {"jerej", 1.0} , { "NO_Name", 999}
};

sort(s, s + size, cmp);
for (node* ps = s; ps != s + size ; ++ps)
printf("%f -> %s\n" , ps->aver , ps->name);
return 0;
}

64,648

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧