From d0ff7d70015252ad56c4f03dbf0290aa610cc765 Mon Sep 17 00:00:00 2001 From: Paulo Custodio Date: Fri, 26 May 2023 19:09:30 +0100 Subject: Add C solution --- challenge-026/paulo-custodio/c/ch-2.c | 45 +++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 challenge-026/paulo-custodio/c/ch-2.c diff --git a/challenge-026/paulo-custodio/c/ch-2.c b/challenge-026/paulo-custodio/c/ch-2.c new file mode 100644 index 0000000000..565926e544 --- /dev/null +++ b/challenge-026/paulo-custodio/c/ch-2.c @@ -0,0 +1,45 @@ +/* +Challenge 026 + +Task #2 +Create a script that prints mean angles of the given list of angles in degrees. +Please read wiki page that explains the formula in details with an example. +*/ + +#include +#include +#include + +void* check_mem(void* p) { + if (!p) { + fputs("Out of memory\n", stderr); + exit(EXIT_FAILURE); + } + return p; +} + +double mean_angle(double *angles, size_t size) { + double y = 0.0, x = 0.0; + for (size_t i = 0; i < size; i++) { + x += cos(angles[i] * M_PI / 180.0); + y += sin(angles[i] * M_PI / 180.0); + } + + return atan2(y / (double)size, x / (double)size) * 180.0 / M_PI; +} + +int main(int argc, char* argv[]) { + if (argc < 2) { + fputs("usage: ch-2 angles...\n", stderr); + return EXIT_FAILURE; + } + + size_t size = argc-1; + double* angles = check_mem(malloc(size * sizeof(double))); + for (size_t i = 0; i < size; i++) + angles[i] = atof(argv[i+1]); + + printf("%.1f", mean_angle(angles, size)); + + free(angles); +} -- cgit