69,373
社区成员
发帖
与我相关
我的任务
分享
#include "stdio.h"
#include "algorithm"
using namespace std;
struct Node
{
double cj;//成绩
int xh;//学号
};
int cmp(const void *a, const void *b)//先按成绩排序,如成绩相同按学号排序(降序)
{
/* struct Node *c = (Node *)a;
struct Node *d = (Node *)b;
if (c->cj >= d->cj)
{
return 1;
}
else
return -1;*/
return (*(Node *)a).cj > (*(Node *)b).cj ? 1:-1;
}
int main()
{
Node node[5];
int i;
int n;
scanf("%d",&n);
for (i = 0; i < n; i++)
{
scanf("%f%d",&node[i].cj,&node[i].xh);
}
qsort(node,n,sizeof(node[0]),cmp);
for(i = 0; i < n; i++)
printf("cj:%f xh:%d\n",node[i].cj,node[i].xh);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
struct node_st {
double score;
int snum;
};
int node_compare(const void *left, const void *right) {
const struct node_st *lnode = (const struct node_st*)left;
const struct node_st *rnode = (const struct node_st*)right;
if (lnode->score < rnode->score)
return -1;
else if (lnode->score > rnode->score)
return 1;
else if (lnode->snum > rnode->snum)
return -1;
else if (lnode->snum < rnode->snum)
return 1;
else
return 0;
}
int main(int argc, char* argv[]) {
struct node_st nodes[5];
int i;
for (i = 0; i < 5; ++ i) {
if (scanf("%lf%d", &nodes[i].score, &nodes[i].snum) != 2) {
return -1;
}
}
qsort(nodes, 5, sizeof(struct node_st), node_compare);
for (i = 0; i < 5; ++ i) {
printf("Index %d => (score : %lf, snum : %d)\n", i, nodes[i].score, nodes[i].snum);
}
return 0;
}
把%f改成%lf就Ok了
#include "stdio.h"
#include "algorithm"
using namespace std;
struct Node
{
double cj;//成绩
int xh;//学号
};
int cmp(const void *a, const void *b)//先按成绩排序,如成绩相同按学号排序(降序)
{
struct Node *c = (Node *)a;
struct Node *d = (Node *)b;
if (c->cj != d->cj)
{
return c->cj - d->cj;
}
else
return d->xh - c->xh;
// return (*(Node *)a).cj - (*(Node *)b).cj;
}
int main()
{
Node node[5];
int i;
int n;
scanf("%d",&n);
for (i = 0; i < n; i++)
{
scanf("%lf %d",&node[i].cj, &node[i].xh); //把%f改成%lf就Ok了
}
qsort(node,n,sizeof(node[0]),cmp);
for(i = 0; i < n; i++)
printf("cj:%f xh:%d\n",node[i].cj,node[i].xh);
return 0;
}