The C language uses radians instead of degrees when calculating angles. Humans should use radians as well, as they’re logical and easy to work with (radians, not humans). What surprises me, however, is that the C library lacks a defined constant for making the degree-radian conversion.
You can bone on up radians with this blog post from two years ago. This information won’t help you do the conversions in C, not as much as having a defined constant would.
For example, the math.h
header file defines the M_PI
constant, which represents the value of π. Just include math.h
in your source code, and you can use M_PI
to represent π without having to rely upon your Mensa friend who is odious but has memorized π out to the 250th digit.
For the conversion between radians and degrees, however, you must rely upon written documentation — or that same odious nerd — to know these two formulas:
Radians / 0.017453 = degrees
Degrees / 57.29578 = radians
So when Joe User types 180 degrees into your trigonometric program, you must convert this value into radians to use the various C library trig functions:
radians = joe_user_degree_input / 57.29578;
My argument is that it would be easier to plug in a defined constant, which is oddly missing from the math.h
header. So why not create your own?
The following code uses the M_PI
constant from math.h
to calculate two new defined constants, RAD2DEG
for converting radians to degrees, and DEG2RAD
for converting degrees to radians.
2020_05_23-Lesson.c
#include <stdio.h> #include <math.h> #ifndef M_PI #define M_PI 3.141592 #endif #define RAD2DEG M_PI/360.0*2.0 #define DEG2RAD 360.0/M_PI/2.0 int main() { printf("Convert radians to degrees: %f\n",RAD2DEG); printf("Convert degrees to radians: %f\n",DEG2RAD); return(0); }
Lines 4 through 6 ensure that the M_PI
defined constant exists. If not, Line 5 defines it as a single-precision value — good enough for most common trig problems.
Line 7 declares the RAD2DEG
defined constant, and Line 8 declares the DEG2RAD
constant.
Here’s the output:
Convert radians to degrees: 0.017453
Convert degrees to radians: 57.295780
Yes, it probably would be easier to just declare both defined constants like this:
#define RAD2DEG 0.017453
#define DEG2RAD 57.295780
This approach is cleaner, and it’s how the math.h
header file defines other mathematical constants; values are specified directly. Still, if somehow the value of π changes in the universe, the approach shown in the sample code remains valid. You never want to take a chance.