【发布时间】:2021-10-13 18:59:47
【问题描述】:
我是 C 的初学者并且遇到了这个问题:我应该制作一个应用程序,您可以在其中插入三角形顶点的坐标,然后打印有关其面积、周长的详细信息,最有趣的是,它是应该打印它的角度。该代码应该使用 Heron 公式中的双正切方程编写。我尝试过使用atan(),但我想我应该添加+n 以避免超出域。虽然不知道怎么样。
Here's the equation。以下是我的代码:
#include <stdio.h>
#include <math.h>
#define PI (4. * atan(1))
int main() {
// Defining floats
float xa, ya, xb, yb, xc, yc, s, P, a, b, c, x, y, z, alphadeg, alpharad, betadeg, betarad, gammadeg, gammarad;
// Inserting coordinates of each points
printf("Insert the first point's coordinates (a space should be between the X and Y coordinate):\n");
scanf("%f %f", &xa, &ya);
printf("Insert the second point's coordinates (a space should be between the X and Y coordinate):\n");
scanf("%f %f", &xb, &yb);
printf("Insert the third point's coordinates (a space should be between the X and Y coordinate):\n");
scanf("%f %f", &xc, &yc);
// Calculating and printing length of each side
printf("Distance between point 1 and 2: %f\n", sqrt(pow(xa - xb, 2) + pow(ya - yb, 2)));
printf("Distance between point 1 and 3: %f\n", sqrt(pow(xa - xc, 2) + pow(ya - yc, 2)));
printf("Distance between point 2 and 3: %f\n", sqrt(pow(xb - xc, 2) + pow(yb - yc, 2)));
// Defining each side
a = sqrt(pow(xa - xb, 2) + pow(ya - yb, 2));
b = sqrt(pow(xa - xc, 2) + pow(ya - yc, 2));
c = sqrt(pow(xb - xc, 2) + pow(yb - yc, 2));
// Defining s as the parameter from Heron's formula
s = ((a + b + c) / 2);
// Defining P as the area from Heron's formula
P = sqrt(s * (s - a) * (s - b) * (s - c));
// Printing the area and perimeter of the triangle
printf("The area of your triangle is %f\n", P);
printf("The perimeter of your triangle is %f\n", a + b + c);
// Angles
/*
tan(alpha/2)=sqrt(((P-b)*(P-c))/(P*(P-a)));
tan(beta/2)=sqrt(((P-a)*(P-c))/(P*(P-b)));
tan(gamma/2)=sqrt(((P-a)*(P-a))/(P*(P-c)));
Let
x = tan(alpha/2)
y = tan(beta/2)
z = tan(gamma/2)
*/
x = sqrt(((P - b) * (P - c)) / (P * (P - a)));
y = sqrt(((P - a) * (P - c)) / (P * (P - b)));
z = sqrt(((P - a) * (P - b)) / (P * (P - c)));
alphadeg = (atan(x)) * 360 / PI;
betadeg = (atan(y)) * 360 / PI;
gammadeg = (atan(z)) * 360 / PI;
alpharad = 2 * (atan(x));
betarad = 2 * (atan(y));
gammarad = 2 * (atan(z));
printf("The value of the alpha angle is %0.3f\n", alphadeg);
printf("The value of the beta angle is %0.3f\n", betadeg);
printf("The value of the gamma angle is %0.3f\n", gammadeg);
printf("%f = %f", PI, (alpharad + betarad + gammarad));
return 0;
}
【问题讨论】:
-
注意:从弧度转换为度数,乘以 180/PI,而不是 360
-
这个问题漏掉了:你的测试用例是什么,预期的结果是什么,实际的结果是什么。
-
我不确定您所说的
+n或“走出域”是什么意思。您是否担心sqrt(((P-b)*(P-c))/(P*(P-a)))之类的计算,其中P*(P-a)可能为零或非常接近于零?这就是atan2函数的用途。所以你可以做alpha = atan2(sqrt((P-b)*(P-c)), sqrt(P*(P-a));。 -
建议
#define PI 3.14159265358979323846而不是4. * atan(1)来删除计算(尽管编译器应该为你优化)。对于所有实际目的,这些值都是相同的。如果使用 gcc/clang,您可以在包含math.h并定义_GNU_SOURCE之后使用预定义的M_PI作为 PI 的值。 -
@TimRandall True,但请注意 OP 需要将该角度加倍。
标签: c trigonometry