Advertisement
scooterone

Overengineered solution to Stupid problem

Oct 18th, 2019
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.02 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. // Structs definition
  4. typedef struct Point {
  5.   float x;
  6.   float y;
  7. } point;
  8.  
  9. typedef struct Line {
  10.   float a;
  11.   float c;
  12.   float from;
  13.   float to;
  14. } line;         //f(x) = ax + c in [from, to]
  15.  
  16.  
  17. // Global variables definition
  18. line parts[3];
  19.  
  20.  
  21. // Functions defintion
  22. line solver(point, point);
  23. float solution(float);
  24.  
  25.  
  26.  
  27. int main() {
  28.   point Data[4] = {{0, 0}, {15, 20}, {27, 55}, {35, 100}};
  29.  
  30.   for (int i=0; i<3; i++) {
  31.     parts[i] = solver(Data[i], Data[i+1]);
  32.   }
  33.  
  34.   float x;
  35.  
  36.   scanf("%f", &x);
  37.   printf("%f\n", solution(x));
  38.  
  39.   return 0;
  40. }
  41.  
  42.  
  43.  
  44. // Creates each part of the function
  45. line solver(point p, point q) {
  46.   float a = (q.y - p.y)/(q.x - p.x);
  47.   float c = p.y - a*p.x;
  48.  
  49.   line f = {
  50.     .a = a,
  51.     .c = c,
  52.     .from = p.x,
  53.     .to = p.y,
  54.   };
  55.  
  56.   return f;
  57. }
  58.  
  59.  
  60. // This is The Function
  61. float solution(float x) {
  62.   for (int i=0; i<3; i++) {
  63.     line p = parts[i];
  64.     if (x>=p.from && x<=p.to) {
  65.       return (p.a*x + p.c);
  66.     }
  67.   }
  68.   return -1;
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement