C 编程中根据给定边求三角形的角度

Mus*_*fat 3 c math

我在我的 code::blocks 中运行它来显示三角形的 3 个角度,其中 3 条边由用户给出。但如果我运行并给出 3 个边,例如 3,4,5,输出将是 -1.#J -1.#J -1.#J。我的代码有什么问题吗?

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

int main()
{
    float a, b, c, A, B, C, R, s, pi, area;
    pi = acos(-1);

    scanf("%f %f %f", &a, &b, &c);
    s = (a+b+c)/2;
    area = sqrt(s*(s-a)*(s-b)*(s-c));

    R = (a*b*c)/(4*area);

    A = (180/pi)*asin(a/2*R);
    B = (180/pi)*asin(b/2*R);
    C =  (180/pi)*asin(c/2*R);

    printf("%.2f %.2f %.2f", A, B, C);


    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*ler 5

您需要更多括号。你有:

A = (180/pi)*asin(a/2*R);
Run Code Online (Sandbox Code Playgroud)

你需要:

A = (180/pi)*asin(a/(2*R));
Run Code Online (Sandbox Code Playgroud)

你写的相当于:

A = (180 / pi) * asin((R * a) / 2);
Run Code Online (Sandbox Code Playgroud)

例如,您还应该检查您的输入,以便拒绝边长为 1、1、3 的“三角形”。负长度和零长度可能也应该被拒绝。

修改后的代码

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

int main(void)
{
    float a, b, c, A, B, C, R, s, pi, area;
    pi = acos(-1);

    if (scanf("%f %f %f", &a, &b, &c) != 3)
    {
        fprintf(stderr, "Failed to read 3 numbers\n");
        return 1;
    }
    if (a <= 0 || b <= 0 || c <= 0)
    {
        fprintf(stderr, "Sides must be strictly positive\n");
        return 1;
    }
    s = (a + b + c) / 2;
    if (a > s || b > s || c > s)
    {
        fprintf(stderr, "The three sides %.2f, %.2f, %.2f do not form a triangle\n",
                a, b, c);
        return 1;
    }

    area = sqrt(s * (s - a) * (s - b) * (s - c));

    R = (a * b * c) / (4 * area);

    A = (180 / pi) * asin(a / (2 * R));
    B = (180 / pi) * asin(b / (2 * R));
    C = (180 / pi) * asin(c / (2 * R));

    printf("Sides:  %6.2f %6.2f %6.2f\n", a, b, c);
    printf("Angles: %6.2f %6.2f %6.2f\n", A, B, C);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

请注意,错误消息是在标准错误上报告的。输出的所有行都以格式中的换行符结尾。输入数据被回显。所有这些都是好的做法。

运行示例

$ triangle <<< "0 1 3"
Sides must be strictly positive
$ triangle <<< "-1 1 3"
Sides must be strictly positive
$ triangle <<< "1 1 3"
The three sides 1.00, 1.00, 3.00 do not form a triangle
$ triangle <<< "3 4 5"
Sides:    3.00   4.00   5.00
Angles:  36.87  53.13  90.00
$ triangle <<< "3 3 3"
Sides:    3.00   3.00   3.00
Angles:  60.00  60.00  60.00
$ triangle <<< "1 1.4141 1"
Sides:    1.00   1.41   1.00
Angles:  45.00    nan  45.00
$ triangle <<< "1 1 1.4141"
Sides:    1.00   1.00   1.41
Angles:  45.00  45.00    nan
$ triangle <<< "1 1 1.414"
Sides:    1.00   1.00   1.41
Angles:  45.01  45.01  89.98
$ triangle <<< "1 1 1.41421356237309504880"
Sides:    1.00   1.00   1.41
Angles:  45.00  45.00    nan
$
Run Code Online (Sandbox Code Playgroud)

我对价值观有点困惑nan。然而,将数据类型从 更改为float并适当double调整scanf()格式(%lf而不是%f)似乎可以“解决”(也许“逃避”是一个更好的词)该问题。