Advertisement
aaaaaa123456789

JV programming challenges, week 6, challenge 2

Dec 22nd, 2013
215
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.99 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <math.h>
  4. #include "common.h"
  5.  
  6. void get_coords(const char *, long double *, long double *);
  7. long double get_value(const char *);
  8.  
  9. #define pi 3.1415926535897932384626433832795029L
  10.  
  11. inline long double square (long double number) {
  12.   return number * number;
  13. }
  14.  
  15. int main (void) {
  16.   long double x1, x2, y1, y2;
  17.   get_coords("First circle:  ", &x1, &y1);
  18.   get_coords("Second circle: ", &x2, &y2);
  19.   long double scale = get_value("Radius:        ");
  20.   long double distance = sqrtl(square(x2 - x1) + square(y2 - y1));
  21.   distance /= scale;
  22.   if (distance >= 2.0L) {
  23.     printf("no overlap\n");
  24.     return 0;
  25.   }
  26.   long double overlap = pi - distance * sqrtl(1.0L - 0.25L * square(distance)) - 2.0L * asinl(0.5L * distance);
  27.   long double area = (2.0L * pi - overlap) * square(scale);
  28.   printf("Area: %.10Lg\n", area);
  29.   return 0;
  30. }
  31.  
  32. void get_coords (const char * prompt, long double * x, long double * y) {
  33.   char * line;
  34.   char ** tokens;
  35.   while (1) {
  36.     printf("%s", prompt);
  37.     line = get_line(NULL);
  38.     tokens = tokenize_string(line, " ", 1);
  39.     free(line);
  40.     if (count_lines(tokens) != 2) {
  41.       free(tokens);
  42.       printf("Please enter two coordinates.\n");
  43.       continue;
  44.     }
  45.     *x = strtold(*tokens, &line);
  46.     if (*line) {
  47.       free(tokens);
  48.       printf("Please enter a valid value for the X coordinate.\n");
  49.       continue;
  50.     }
  51.     *y = strtold(tokens[1], &line);
  52.     if (*line) {
  53.       free(tokens);
  54.       printf("Please enter a valid value for the Y coordinate.\n");
  55.       continue;
  56.     }
  57.     free(tokens);
  58.     return;
  59.   }
  60. }
  61.  
  62. long double get_value (const char * prompt) {
  63.   char * line;
  64.   char * errp;
  65.   long double result;
  66.   while (1) {
  67.     printf("%s", prompt);
  68.     line = get_line(NULL);
  69.     result = strtold(line, &errp);
  70.     if (*errp || (result <= 0.0L)) {
  71.       free(line);
  72.       printf("Please enter a valid value.\n");
  73.       continue;
  74.     }
  75.     free(line);
  76.     return result;
  77.   }
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement