我尝试给数据排名,但结果不是我的预期。我的{}如下:
for(i = 0; i < 100; i++)
{
int curRank=1;
for (j = 0; j < i; j++)
// add x[i] to list, need to update the ranks.
{
if (x[i] > x[j])
{ // Update rank of x[i]
curRank++;
}
else
{ // A number smaller than x[j] has appeared. Update rank of x[j]
rank[j]++;
}
}
rank[i]=curRank;
printf("%lf %d\n", x[i],rank[i]);
}
结果如下:
30.000000 1
71.510000 2
3.300000 1
87.440000 4
53.420000 3
63.160000 4
89.100000 7
25.750000 2
.......
显然,这是错误的。任何人都可以帮我这个吗?谢谢。
答案 0 :(得分:3)
您的算法有效,但在处理完所有值后,排名尚未完成。因此,您无法随时打印排名。你必须在一个单独的循环中完成算法后打印等级:
double x[8] = {30, 71.51, 3.3, 87.44, 53.42, 63.16, 89.1, 25.75};
int rank[8] = {0};
int i, j;
for (i = 0; i < 8; i++) {
int curRank = 1;
for (j = 0; j < i; j++) {
if (x[i] > x[j]) {
curRank++;
} else {
rank[j]++;
}
}
rank[i] = curRank;
}
for (i = 0; i < 8; i++) {
printf("%lf %d\n", x[i], rank[i]);
}