diff options
Updated exercise 0 with epsilon comparison in homework1.cpp
1 files changed, 28 insertions, 14 deletions
| -rw-r--r-- | Year 1/Programming introduction/Homeworks/homework1.cpp | 42 |
diff --git a/Year 1/Programming introduction/Homeworks/homework1.cpp b/Year 1/Programming introduction/Homeworks/homework1.cpp index f443cb9..b0eed83 100644 --- a/Year 1/Programming introduction/Homeworks/homework1.cpp +++ b/Year 1/Programming introduction/Homeworks/homework1.cpp @@ -8,6 +8,20 @@ using namespace std; * Exercise 0 */ +double const FLOAT_EPSILON_FLOOR = 0.0001, FLOAT_EPSILON_CEIL = FLOAT_EPSILON_FLOOR * 9; + +bool eq(double a, double b) { + return ((a - b) < 0.0 ? (b - a) : (a - b)) <= FLOAT_EPSILON_FLOOR; +} + +bool lt(double a, double b) { + return !eq(a, b) && (a - b) < FLOAT_EPSILON_CEIL; +} + +bool mt(double a, double b) { + return lt(b, a); +} + double distanceBetweenPoints(int x1, int y1, int x2, int y2) { int sideA = x1 - x2, sideB = y1 - y2; @@ -24,41 +38,41 @@ void ex0() { double x, y; cin >> x >> y; - if (x == 0) // if it's on the Y ordinate + if (eq(x, 0)) // if it's on the Y ordinate cout << "On a line" << endl; - else if (distanceBetweenPoints(0, 0, x, y) < 4.0) { - float pointSlope = y / x; + else if (lt(distanceBetweenPoints(0, 0, x, y), 4.0)) { + double pointSlope = y / x; - if (x == -2.828 || x == 2.828 || pointSlope == SLOPE_B || pointSlope == SLOPE_C || pointSlope == SLOPE_D || pointSlope == SLOPE_E) + if (eq(x, -2.828) || eq(x, 2.828) || eq(pointSlope, SLOPE_B) || eq(pointSlope, SLOPE_C) || eq(pointSlope, SLOPE_D) || eq(pointSlope, SLOPE_E)) cout << "On a line" << endl; - else if (y >= 0 && x > 0) { // Check 1st quadrant - if (pointSlope > SLOPE_B) + else if ((mt(y, 0) || eq(y, 0)) && mt(x, 0)) { // Check 1st quadrant + if (mt(pointSlope, SLOPE_B)) cout << "Inside green area!" << endl; - else if (x > 2.828) + else if (mt(x, 2.828)) cout << "Inside purple area!" << endl; else cout << "Inside yellow area!" << endl; } - else if (y >= 0 && x < 0) { // Check 2nd quadrant - if (pointSlope < SLOPE_D) + else if ((mt(y, 0) || eq(y, 0)) && lt(x, 0)) { // Check 2nd quadrant + if (lt(pointSlope, SLOPE_D)) cout << "Inside red area!" << endl; else if (x > -2.828) cout << "Inside pink area!" << endl; } - else if (y < 0 && x < 0) { // Check 3rd quadrant - if (pointSlope > SLOPE_C) + else if (lt(y, 0) && lt(x, 0)) { // Check 3rd quadrant + if (mt(pointSlope, SLOPE_C)) cout << "Inside blue area!" << endl; - else if (x > -2.828) + else if (mt(x, -2.828)) cout << "Inside pink area!" << endl; } else { // Check 4th quadrant - if (pointSlope > SLOPE_E && x > 2.828) + if (mt(pointSlope, SLOPE_E) && mt(x, 2.828)) cout << "Inside purple area!" << endl; else cout << "Inside yellow area!" << endl; } } - else if ((-2.0 < x && x < 2.0) && (-6.0 < y && y < -7.0)) // outside circle and in rectangle + else if ((lt(-2, x) && lt(x, 2)) && (lt(-6, y) && lt(y, -7))) // outside circle and in rectangle cout << "Inside grey area" << endl; } |
