Advertisement
Guest User

Second exercise

a guest
Jan 20th, 2020
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.21 KB | None | 0 0
  1. #include <iostream>
  2. #include<vector>
  3.  
  4. using namespace std;
  5.  
  6. class NegativeNumberException{
  7. private:
  8.     int index;
  9.     int value;
  10. public:
  11.     explicit NegativeNumberException(int i, int v) : index(i), value(v) {};
  12.     int get_index() const {return index;}
  13.     int get_value() const {return value;}
  14. };
  15.  
  16. ostream &operator<<(ostream &os, NegativeNumberException nn){
  17.     os<<"Negative number at " << nn.get_index() << " position with " << nn.get_value() << " value"<<endl;
  18.     return os;
  19. }
  20.  
  21. class Total{
  22. private:
  23.     bool omit_negative = true;
  24. public:
  25.     explicit Total(bool omit) : omit_negative(omit) {};
  26.     int total(int [], int);
  27.  
  28. };
  29. int Total::total(int tab[], int n){
  30.     int total=0;
  31.     for(int i = 0; i<n; i++){
  32.         if(tab[i]<0)
  33.             if(!omit_negative) throw NegativeNumberException(i,tab[i]);
  34.         total+=tab[i];
  35.     }
  36.     return total;
  37. }
  38.  
  39. int main() {
  40.     int tab[5] = {1, 2, 3, -1, 5};
  41.     bool choice;
  42.     cout<<"Do u want to consider negative numbers: 0)no 1)yes"<<endl;
  43.     cin >> choice;
  44.     Total total_calculator(choice);
  45.     try{
  46.         cout<<total_calculator.total(tab, 5);
  47.     }catch(NegativeNumberException nn){
  48.         cout<<nn;
  49.     }
  50.     return 0;
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement