gpt4 book ai didi

HackerRank 网站中的 Clang 问题 "Small Triangles, Large Triangles"

转载 作者:行者123 更新时间:2023-11-30 16:12:50 24 4
gpt4 key购买 nike

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

You are given triangles, specifically, their sides a, b and c. Print them in the same style but sorted by their areas from the smallest one to the largest one. It is guaranteed that all the areas are different.

The best way to calculate a volume of the triangle with sides a,b and c is Heron's formula.

这是我的代码:

#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

最佳答案

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

conversion from 'double' to 'int', possible loss of data

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

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

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

应该是

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

关于HackerRank 网站中的 Clang 问题 "Small Triangles, Large Triangles",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58241073/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com