在 C 中不排序的情况下为列表提供排名 [英] Give ranks to a list without sorting in C

查看:42
本文介绍了在 C 中不排序的情况下为列表提供排名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试对数据进行排名,但结果不是我所期望的.我的 {} 如下:

I try to give the rank to the data, but the result is not what i expected.My for {} is as below :

    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
.......

显然,这是错误的.有人可以帮我解决这个问题吗?谢谢.

Clearly, it is wrong. Could anyone help me with this? Thank you.

推荐答案

您的算法有效,但在处理完所有值后排名并不完整.因此,您无法随时打印行列.您必须在单独的循环中完成算法后打印排名:

Your algorithm works, but the ranking isn't complete after all values have been processed. Therefore, you can't print the ranks as you go. You must print the ranks after your algorihm is done in a separate loop:

    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]);
    }

这篇关于在 C 中不排序的情况下为列表提供排名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆