首页 > 解决方案 > HackerRank 网站中的 Clang 问题“Small Triangles, Large Triangles”

问题描述

我一直在尝试用 C 语言解决 HackerRank 网站中的“小三角形,大三角形”问题,这是一种排序数组问题,我使用了选择排序算法。我的代码似乎正在运行,但它仅适用于某些测试用例。这是任务:

给定三角形,特别是它们的边 a、b 和 c。以相同的样式打印它们,但按面积从最小到最大排序。保证所有区域都是不同的。

计算边为 a、b 和 c 的三角形体积的最佳方法是 Heron 公式。

这是我的代码:

#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[n];
    int p[n];
    int temp[3];
    int min;
    double doubledArea[n];
    //calculate the volume
    for(int i = 0; i < n; i++)
    {
        // volume = 0.5 * (H * W * L)
        p[i] = (tr[i].a + tr[i].b + tr[i].c) * 0.5;
        doubledArea[i] = p[i]*(p[i]-tr[i].a)*(p[i]-tr[i].b)*(p[i]-tr[i].c);
        area[i] = sqrt(doubledArea[i]);
    }
    //sort by volume
    for(int i = 0; i < n; i++)
    {
        min = i;
        for (int j = i+1; j < n; j++)
        if(area[j] < area[min])
        {
            min = j;
            temp[0] = tr[i].a;
            temp[1] = tr[i].b;
            temp[2] = tr[i].c;
            tr[i].a = tr[min].a;
            tr[i].b = tr[min].b;
            tr[i].c = tr[min].c;
            tr[min].a = temp[0];
            tr[min].b = temp[1];
            tr[min].c = temp[2];
        }
    }
}

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

当我尝试例如:

3
9 8 9 
4 5 7
2 5 4

它有效,但不适用于以下输入:

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

标签: c

解决方案


您将浮点计算的结果存储在int数组中 - 这是一个错误,正如编译器警告的那样:

从 'double' 到 'int' 的转换,可能会丢失数据

因此,say 的区域9.2不会被认为小于,9.3因为它们都存储为9.

计算期间使用的数组应该是double. 所以这两个数组

int area[n];
int p[n];

应该

double area[n];
double p[n];

推荐阅读