已知斜边与角度求解对边:C语言代码错误排查咨询
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

