Antun Tun
Antun Tun

Reputation: 1539

Is there a function in C language to calculate degrees/radians?

I need to calculate an angle in C programm. Here is a method from JAVA that I need to convert to C.

private static double calculateDirection(double x, double y)
{
    return Math.toDegrees(Math.atan2(y, x));
}

Is there a function like toDegrees in C language so I don't have to write all the code by myself? Thank you

Upvotes: 33

Views: 81169

Answers (3)

Demitri
Demitri

Reputation: 14039

If your preference is to just copy/paste a couple of macros:

#include <math.h>
#define degToRad(angleInDegrees) ((angleInDegrees) * M_PI / 180.0)
#define radToDeg(angleInRadians) ((angleInRadians) * 180.0 / M_PI)

And if you want to omit the #include, replace that line with this which was copied from the math.h header:

#define M_PI   3.14159265358979323846264338327950288

Upvotes: 5

Emanuele Paolini
Emanuele Paolini

Reputation: 10162

#include <math.h>

inline double to_degrees(double radians) {
    return radians * (180.0 / M_PI);
}

Upvotes: 46

antonijn
antonijn

Reputation: 5760

There is no need to use such a method. Converting to degrees is very simple:

double radians = 2.0;
double degrees = radians * 180.0 / M_PI;

Turn that into a function if you want to.

M_PI is* defined in math.h by the way.


* in most compilers.

Upvotes: 9

Related Questions