c - 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
解决方案
您将浮点计算的结果存储在int
数组中 - 这是一个错误,正如编译器警告的那样:
从 'double' 到 'int' 的转换,可能会丢失数据
因此,say 的区域9.2
不会被认为小于,9.3
因为它们都存储为9
.
计算期间使用的数组应该是double
. 所以这两个数组
int area[n];
int p[n];
应该
double area[n];
double p[n];
推荐阅读
- matrix - 如何用 incanter 改变矩阵的元素?
- sql - 在 Postgresql 中比较字符串日期的最有效方法?
- python - test_first 字符串索引必须是整数
- mongodb - 如何查询一个集合中的值是否作为字符串出现在第二个集合的字段值中?
- c# - Visual Studio 2019 Preview Intelisense 显示红线曲线,但在使用 .NET 5 的 C# 库项目中成功编译
- java - 有没有办法让我在 podConter() 方法中操作这个 7 ?
- haskell - 以特定间隔拆分列表或字符串的多态函数
- c# - ViewBag ASP NET CORE MVC | CallSite.Target(闭包,CallSite,对象)
- react-native - React Native:WebView 无响应的网页
- c# - 尝试读取标准输出时进程挂起