How to convert a degree to a compass direction in C

1 Answer

0 votes
/*
0° → North
45° → North-East
90° → East
135° → South-East
180° → South
225° → South-West
270° → West
315° → North-West
*/
 
#include <stdio.h>
#include <math.h>
 
const char *degreesToDirection(double degrees) {
    // Normalize degrees to (0, 360)
    degrees = fmod(degrees + 360.0, 360.0);
 
    // Define compass directions
    static const char *directions[8] = {
        "North", "North-East", "East", "South-East",
        "South", "South-West", "West", "North-West"
    };
 
    // Each direction covers 45 degreess
    //int index = (int)((degrees / 45.0) + 0.5) % 8;
    int index = (int)((degrees + 22.5) / 45.0) % 8;
 
    return directions[index];
}
 
int main(void) {
    double degrees = 120.0;
 
    printf("For %.2lf degrees, Compass direction: %s\n", degrees, degreesToDirection(degrees));
 
    return 0;
}
 
  
   
/* 
run:
   
For 120.00 degrees, Compass direction: South-East
 
*/

 



answered Nov 24, 2025 by avibootz
edited Nov 24, 2025 by avibootz
...