You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

已知斜边与角度求解对边:C语言代码错误排查咨询

Why Your Opposite Side Calculation Isn't Working

Hey there! I can spot the issue right away—your code is using degrees with the sin() function, but it expects radians instead. That's why the results are way off from what you'd expect.

The Core Problem

C's standard library math.h functions like sin(), cos(), and tan() all operate on radian measurements, not the degrees we use for everyday geometry. For example, if you input 90 degrees into sin(), it treats that as 90 radians (roughly 5156 degrees!), so the sine value will be nowhere near the expected 1. That mismatch is why your calculation fails.

How to Fix It

You need to convert your input angle from degrees to radians first. The conversion formula is straightforward:
radians = degrees × π / 180

Here are two solid ways to adjust your code:

Option 1: Define π manually

If you don't want to rely on compiler-specific constants, define your own precise value for pi:

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

// Define a precise value for π
#define PI 3.14159265358979323846

int main () {
    double fAngle, fHyp;
    printf("Angle: ");
    scanf("%lf", &fAngle);
    printf("Hypotenuse: ");
    scanf("%lf", &fHyp);
    
    // Convert degrees to radians before calculating sine
    double radians = fAngle * PI / 180.0;
    printf("The opposite side is %lf", sin(radians) * fHyp);
    return 0;
}

Option 2: Use the predefined M_PI constant

Most compilers provide M_PI in math.h, but you need to define _USE_MATH_DEFINES before including math.h to enable it:

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

int main () {
    double fAngle, fHyp;
    printf("Angle: ");
    scanf("%lf", &fAngle);
    printf("Hypotenuse: ");
    scanf("%lf", &fHyp);
    
    double radians = fAngle * M_PI / 180.0;
    printf("The opposite side is %lf", sin(radians) * fHyp);
    return 0;
}

Test It Out

If you input 30 degrees and a hypotenuse of 2, the corrected code should output 1.000000—the exact opposite side length you'd expect for that right triangle.

内容的提问来源于stack exchange,提问作者Mere Pixel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.01 00:32:40