You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Hackerrank Small Triangles问题代码仅过单测试用例,求故障原因

问题:Hackerrank 三角形面积排序代码仅通过部分测试用例

我编写了C语言代码解决Hackerrank的Small Triangles, Large Triangles问题,其中sort_by_area函数用于按面积对三角形数组排序。目前代码仅通过了一个测试用例:

通过的测试用例:

3
7 24 25
5 12 13
3 4 5

但其他测试用例全部失败,比如下面这个包含10个三角形的测试用例:

失败的测试用例:

10
67 67 19
3 57 55
33 33 49
61 58 59
23 43 35
48 42 45
23 12 27
41 34 22
26 49 35
63 46 45

我的代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

struct triangle
{
    int a;
    int b;
    int c;
};

typedef struct triangle triangle;
void sort_by_area(triangle* tr, int n) {
    /*
    * Sort an array a of the length n
    */
    int area_i ,area_j,i,j;
    for(i=0;i<n;i++){
        for(j=i+1;j<n;j++){
            area_i = (tr[i].a+tr[i].b+tr[i].c)/2;
            area_j = (tr[j].a+tr[j].b+tr[j].c)/2;
            if(area_i>area_j){
                struct triangle temp = tr[i];
                tr[i] = tr[j];
                tr[j] = temp;
            }
            
        }
    }

}

int main()
{
    int n;
    scanf("%d", &n);
    triangle *tr = malloc(n * sizeof(triangle));
    for (int i = 0; i < n; i++) {
        scanf("%d%d%d", &tr[i].a, &tr[i].b, &tr[i].c);
    }
    sort_by_area(tr, n);
    for (int i = 0; i < n; i++) {
        printf("%d %d %d\n", tr[i].a, tr[i].b, tr[i].c);
    }
    return 0;
}

我不想直接要现成的解决方案,希望有人帮我分析下自己的实现思路存在什么问题。

内容的提问来源于stack exchange,提问作者Anik Chakraborty

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 21:35:18