C++ handles trigonometry very easily - all the programmer has to do is to load the correct header (math.h) and start using the trigonometric functions (cos, sin and tan). However, as often is the case, the C++ trigonometric functions work with radians and not degrees; that may not be an issue, but if it is then the solution is simple - just write a set of trigonometric functions that work with degrees instead of radians.
There is, of course, no need to rewrite the C++ trigonometric functions - it is just a case of writing wrappers for each of the existing functions that will:
- allow the user to enter a value in degrees
- convert the degrees into radians
- use the existing trigonometric functions to return the cosine, sine or tangent to the user
A similar process will also be needed for the inverse trigonometric functions:
- allow the user to enter a cosine, sine or tangent
- use the existing inverse trigonometric functions to obtain the result in radians
- convert the radians into degrees
- return value in degrees to the user
Converting from Degrees to Radians and Vice Versa
The only completely new functionality that the programmer needs introduce is the conversion from degrees to radians and from radians to degrees; however, the calculation is very simple:
The first job (as always) when programming functions is to create a header file (for example trig.h):
Of course only the function declarations are placed in the header file - the code for the actual functionality is placed in it's own file (for example trig.c):
With the degree-radian-degree conversion in place the programmer can turn to the trigonometric functions themselves.
Trigonometric Functions
The user defined trigonometric functions simply take an input in degrees, convert the value into radians and then return the results of the C++ trigonometric functions, and again the first step is to add function declarations to the header file:
And then to write the code for the functions into the source file:
Inverse Trigonometric Functions
The user defined inverse trigonometric functions convert the cosine, sine or tangent into degrees - and again must start with a declaration in the header file:
And the actual coding in the source file:
Testing the Functions: a Trigonometric Program for Calculating the Sine of an Angle
With the declarations in a header files the functions can be called from other programs for example one to calculate the sine of a angle on the command line, for example sine.c:
Once the program has been compiled then it will produce an output something like:
Summary
C++ has its own trigonometric functions and inverse trigonometric functions but these only work in radians - user defined functions are required in order for the trigonometric functions to accept degrees as inputs. The functions need to be declared in a header file so they can be called from any further C++ programs that are written.