// 22.5HV2 Software Engineering II // Unit 3 Exercise 3 #include "change.h" // contains #include #include ostream& operator<<(ostream& outs, const Change& c) { outs << endl << setw(10) << c.one_p << " x 1p" << endl; outs << setw(10) << c.two_p << " x 2p" << endl; outs << setw(10) << c.five_p << " x 5p" << endl; outs << setw(10) << c.ten_p << " x 10p" << endl; outs << setw(10) << c.twenty_p << " x 20p" << endl; outs << setw(10) << c.fifty_p << " x 50p" << endl; outs << setw(10) << c.pound << " x pound coin" << endl; return outs; } istream& operator>>(istream& ins, Change& c) { cout << endl << "Enter number of one pence coins: "; ins >> c.one_p; cout << "Enter number of two pence coins: "; ins >> c.two_p; cout << "Enter number of five pence coins: "; ins >> c.five_p; cout << "Enter number of ten pence coins: "; ins >> c.ten_p; cout << "Enter number of twenty pence coins: "; ins >> c.twenty_p; cout << "Enter number of fifty pence coins: "; ins >> c.fifty_p; cout << "Enter number of pound coins: "; ins >> c.pound; return ins; }; Change::Change(): one_p(0), two_p(0), five_p(0), ten_p(0), twenty_p(0), fifty_p(0), pound(0) {} Change::Change(int one, int two, int five, int ten, int twenty, int fifty, int pnd): one_p(one), two_p(two), five_p(five), ten_p(ten), twenty_p(twenty), fifty_p(fifty), pound(pnd) {} Change::Change(float amount) { int pence = int(100.0*amount), left=pence; pound = pence/100; left %= 100; fifty_p = left/50; left %= 50; twenty_p = left/20; left %= 20; ten_p = left/10; left %= 10; five_p = left/5; left %= 5; two_p = left/2; one_p = left%2; } int Change::pence() const { return one_p + two_p*2 + five_p*5 + ten_p*10 + twenty_p*20 + fifty_p*50 + pound*100; } Change& Change::operator+=(const Change& c) { one_p += c.one_p; two_p += c.two_p; five_p += c.five_p; ten_p += c.ten_p; twenty_p += c.twenty_p; fifty_p += c.fifty_p; pound += c.pound; return *this; } Change& Change::operator-=(float amount) { Change sum=*this; int pennies=int(amount*100), num; if (*thisnum) { pennies-=num*100; sum.pound-=num; } else { pennies-=sum.pound*100; sum.pound=0; } num=pennies/50; if (sum.fifty_p>num) { pennies-=num*50; sum.fifty_p-=num; } else { pennies-=sum.fifty_p*50; sum.fifty_p=0; } num=pennies/20; if (sum.twenty_p>num) { pennies-=num*20; sum.twenty_p-=num; } else { pennies-=sum.twenty_p*20; sum.twenty_p=0; } num=pennies/10; if (sum.ten_p>num) { pennies-=num*10; sum.ten_p-=num; } else { pennies-=sum.ten_p*10; sum.ten_p=0; } num=pennies/5; if (sum.five_p>num) { pennies-=num*5; sum.five_p-=num; } else { pennies-=sum.five_p*5; sum.five_p=0; } num=pennies/2; if (sum.two_p>num) { pennies-=num*2; sum.two_p-=num; } else { pennies-=sum.two_p*2; sum.two_p=0; } if (pennies>sum.one_p) { cout << "I'm sorry - I don't have the correct change" << endl; return *this; } sum.one_p -= pennies; return (*this=sum); } Change::operator float() const { return pence()/100.0; } /* bool Change::operator<(const Change& c) { return ( pence() < c.pence() ); } */