Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include<vector>
- using namespace std;
- class NegativeNumberException{
- private:
- int index;
- int value;
- public:
- explicit NegativeNumberException(int i, int v) : index(i), value(v) {};
- int get_index() const {return index;}
- int get_value() const {return value;}
- };
- ostream &operator<<(ostream &os, NegativeNumberException nn){
- os<<"Negative number at " << nn.get_index() << " position with " << nn.get_value() << " value"<<endl;
- return os;
- }
- class Total{
- private:
- bool omit_negative = true;
- public:
- explicit Total(bool omit) : omit_negative(omit) {};
- int total(int [], int);
- };
- int Total::total(int tab[], int n){
- int total=0;
- for(int i = 0; i<n; i++){
- if(tab[i]<0)
- if(!omit_negative) throw NegativeNumberException(i,tab[i]);
- total+=tab[i];
- }
- return total;
- }
- int main() {
- int tab[5] = {1, 2, 3, -1, 5};
- bool choice;
- cout<<"Do u want to consider negative numbers: 0)no 1)yes"<<endl;
- cin >> choice;
- Total total_calculator(choice);
- try{
- cout<<total_calculator.total(tab, 5);
- }catch(NegativeNumberException nn){
- cout<<nn;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement