Pages - Menu

Monday 8 October 2012

Converting degrees to radians and radians to degrees in C

Degrees to radians


The following C function receives an angle in degrees and returns the equivalent angle in radians.
Note: To use the M_PI constant, you have to:  #define _USE_MATH_DEFINES before including math.h or you can define your own pi constant:  #define PI 3.14159265 
/*
 * Description:
 *  Converts degrees to radians
 * Parameters:
 *  degrees - angle in degrees
 * Returns:
 *  radians - the equivalent angle in radians
 */
float DegreesToRadians(float degrees)
{
    float radians = degrees*M_PI/180;
    return radians;
}

Radians to degrees


The following C function receives an angle in radians and returns the equivalent angle in degrees.
/*
 * Description:
 *  Converts radians to degrees
 * Parameters:
 *  radians - angle in radians
 * Returns:
 *  degrees - the equivalent angle in degrees
 */
float RadiansToDegrees(float radians)
{
    float degrees = radians*180/M_PI;
    return degrees;
}

Example:

This C program takes your option and uses one of the functions above in accordance to your choice to convert the given angle from degrees to radians or conversely.
#include<stdio.h>
#include<conio.h>
#define _USE_MATH_DEFINES
#include<math.h>
#include<stdlib.h>

#define PI 3.14159265

float DegreesToRadians(float degrees);
float RadiansToDegrees(float radians);

int main(void)
{
    int exit = 0, option = 0;
    float degrees = 0, radians = 0, angle = 0;
    while (exit == 0)
    {
        system("cls");
        printf("\n Choose your option: "
               "\n\t[1] Convert degrees to radians"
               "\n\t[2] Convert radians to degrees"
               "\n\t[0] Exit program\n");
        scanf("%d",&option);
        switch (option)
        {
        case 1:
            printf("\n Enter the angle in degrees: ");
            scanf("%f",&degrees);
            angle = DegreesToRadians(degrees);
            printf(" The equivalent angle in radians: %.3f",angle);
            getch();
            break;
        case 2:
            printf("\n Enter the angle in radians: ");
            scanf("%f",&radians);
            angle = RadiansToDegrees(radians);
            printf(" The equivalent angle in degrees: %.3f",angle);
            getch();
            break;
        case 0:
            exit = 1;
            break;
        default:
            printf("\nNo such option. Enter again.");
            getch();
            break;
        }
    }
    printf("\n\nPress any key to exit...");
    getch();
    return 0;
}
Output: 


No comments:

Post a Comment