Advertisement
Lesnic

ITP exceptions 2 my

Apr 11th, 2020
293
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.64 KB | None | 0 0
  1. #include <iostream>
  2. #include <math.h>
  3.  
  4. using namespace std;
  5.  
  6. class Vector {
  7. private:
  8.     int dimension;
  9.     int* array;
  10.  
  11. public:
  12.     Vector() {
  13.         dimension = 0;
  14.         array = NULL;
  15.     }
  16.  
  17.     friend istream& operator >> (istream& cin, Vector& now) {
  18.         cin >> now.dimension;
  19.         now.array = new int[now.dimension];
  20.         for (int i = 0; i < now.dimension; i++)
  21.             cin >> now.array[i];
  22.         return cin;
  23.     }
  24.  
  25.     friend ostream& operator << (ostream& cout, Vector now) {
  26.         for (int i = 0; i < now.dimension; i++)
  27.             cout << now.array[i];
  28.         return cout;
  29.     }
  30.  
  31.     friend int get_distance(Vector, Vector);
  32. };
  33.  
  34. int get_distance(Vector first, Vector second) {
  35.     int result = 0;
  36.     if (first.dimension != second.dimension)
  37.         throw invalid_argument("invalid_argument exception");
  38.  
  39.     bool check = true;
  40.     for (int i = 0; i < first.dimension; i++) {
  41.         check = check && first.array[i] == second.array[i];
  42.         result += pow(first.array[i] - second.array[i], 2);
  43.     }
  44.  
  45.     result = sqrt(result);
  46.  
  47.     if (check)
  48.         throw domain_error("domain_error exception");
  49.  
  50.     if (result >= 100)
  51.         throw length_error("length_error exception");
  52.  
  53.  
  54.     return result;
  55. }
  56.  
  57. int main() {
  58.     Vector first, second;
  59.  
  60.     cin >> first >> second;
  61.  
  62.     try {
  63.         cout << get_distance(first, second);
  64.     }
  65.     catch (invalid_argument & exception) {
  66.         cout << exception.what();
  67.     }
  68.     catch (length_error & exception) {
  69.         cout << exception.what();
  70.     }
  71.     catch (domain_error & exception) {
  72.         cout << exception.what();
  73.     }
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement