Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <iomanip>
- #include <string>
- #include "DallarAmount.h"
- using namespace std;
- int main() {
- DollarAmount d1(123, 45); // $123.45
- DollarAmount d2{1576}; // $15.76
- cout << "After adding d2 (" << d2.toString() << ") into d1 ("
- << d1.toString() << "), d1 = ";
- d1.add(d2); // modifies object d1
- cout << d1.toString() << "\n";
- cout << "After subtracting d2 (" << d2.toString() << ") from d1 ("
- << d1.toString() << "), d1 = ";
- d1.subtract(d2); // modifies object d1
- cout << d1.toString() << "\n";
- cout << "After subtracting d1 (" << d1.toString() << ") from d2 ("
- << d2.toString() << "), d2 = ";
- d2.subtract(d1); // modifies object d2
- cout << d2.toString() << "\n\n";
- cout << "Enter integer interest rate and divisor. For example:\n"
- << "for 2%, enter: 2 100\n"
- << "for 2.3%, enter: 23 1000\n"
- << "for 2.37%, enter: 237 10000\n"
- << "for 2.375%, enter: 2375 100000\n> ";
- int rate; // whole-number interest rate
- int divisor; // divisor for rate
- cin >> rate >> divisor;
- DollarAmount balance{100000}; // initial principal amount in pennies
- cout << "\nInitial balance: " << balance.toString() << endl;
- cout << "\nYear" << setw(20) << "Amount on deposit" << endl;
- for (unsigned int year{1}; year <= 10; year++) {
- balance.addInterest(rate, divisor);
- cout << setw(4) << year << setw(20) << balance.toString() << endl;
- }
- }
- #include <string>
- #include <cmath>
- class DollarAmount {
- public:
- explicit DollarAmount(int64_t value) : amount{value} { }
- explicit DollarAmount(int64_t dollars, int64_t cents){
- amount = ( dollars * 100 + cents ) / 100;
- }
- void add(DollarAmount right) {
- amount += right.amount;
- }
- void subtract(DollarAmount right) {
- amount -= right.amount;
- }
- void addInterest(int rate, int divisor) {
- DollarAmount interest{
- (amount * rate + divisor / 2) / divisor
- };
- add(interest);
- }
- std::string toString() const {
- std::string dollars{std::to_string(amount / 100)};
- std::string cents{std::to_string(std::abs(amount % 100))};
- return dollars + "." + (cents.size() == 1 ? "0" : "") + cents;
- }
- private:
- int64_t amount{0};
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement