home *** CD-ROM | disk | FTP | other *** search
- /*
- C++ program that uses pointers to functions to implement a
- a program that calculates the depreciation of an asset
- */
-
- #include <iostream.h>
- #include <math.h>
-
- enum DeprMethod { StraightLineMethod, DeclineBalanceMethod,
- SumOfDigitsMethod };
-
- double StraightLine(double origVal, double scrapVal,
- unsigned serviceLife, unsigned year)
- {
- double deprRate = (origVal - scrapVal) / serviceLife;
-
- return origVal - year * deprRate;
- }
-
- double DeclineBalance(double origVal, double scrapVal,
- unsigned serviceLife, unsigned year)
- {
- double deprCoef = 1 - pow(scrapVal / origVal,
- 1.0/serviceLife);
-
- return origVal * pow((1 - deprCoef), year);
- }
-
-
- double SumOfDigits(double origVal, double scrapVal,
- unsigned serviceLife, unsigned year)
- {
- long sumYears = serviceLife * (serviceLife + 1) / 2;
- double totalDeprVal = origVal - scrapVal;
- double sumDepr = 0;
-
- for (unsigned i = 1; i <= year; i++)
- sumDepr += totalDeprVal * (serviceLife + 1 - i) / sumYears;
- return origVal - sumDepr;
- }
-
-
- void CalcDeprTable(double origVal, double scrapVal,
- unsigned serviceLife,
- double (*f)(double, double, unsigned, unsigned))
- {
- for (unsigned year = 1; year <= serviceLife; year++)
- cout << "At year " << year << " value is $"
- << (*f)(origVal, scrapVal, serviceLife, year)
- << "\n";
- cout << "\n\n\n";
- }
-
- void GetDouble(const char* prompt, double& x)
- {
- do {
- cout << prompt;
- cin >> x;
- cout << "\n";
- } while (x <= 0);
- }
-
- void GetUnsigned(const char* prompt, unsigned& n)
- {
- do {
- cout << prompt;
- cin >> n;
- cout << "\n";
- } while (n < 1);
- }
-
- DeprMethod SelectDeprFunction()
- {
- int n;
-
- cout << "Select a depreciation method:\n"
- << "1) Straight line\n"
- << "2) Declining balance\n"
- << "3) Sum of digits\n\n";
- cout << "Enter Choice by number: ";
- cin >> n;
- cout << "\n\n";
- switch (n) {
- case 1:
- return StraightLineMethod;
-
- case 2:
- return DeclineBalanceMethod;
-
- case 3:
- return SumOfDigitsMethod;
-
- default:
- return StraightLineMethod;
- }
- }
-
- main()
- {
- double OrigVal;
- double ScrapVal;
- unsigned ServiceLife;
- double (*DeprFun)(double, double, unsigned, unsigned);
- DeprMethod Choice;
- char Answer;
-
- do {
- GetDouble("Enter original value: ", OrigVal);
- GetDouble("Enter scrap value: ", ScrapVal);
- GetUnsigned("Enter service life: ", ServiceLife);
- Choice = SelectDeprFunction();
- switch (Choice) {
- case StraightLineMethod:
- DeprFun = StraightLine;
- break;
- case DeclineBalanceMethod:
- DeprFun = DeclineBalance;
- break;
- case SumOfDigitsMethod:
- DeprFun = SumOfDigits;
- break;
- }
- CalcDeprTable(OrigVal, ScrapVal, ServiceLife, DeprFun);
- cout << "More calculations ? (Y/N) ";
- cin >> Answer;
- cout << "\n";
- } while (Answer == 'Y' || Answer == 'y');
-
- return 0;
- }