home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
C Programming Starter Kit 2.0
/
SamsPublishing-CProgrammingStarterKit-v2.0-Win31.iso
/
tybc4
/
advfun9.cpp
< prev
next >
Wrap
C/C++ Source or Header
|
1993-05-17
|
3KB
|
114 lines
/*
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>
double StraightLine(double origVal, double scrapVal,
unsigned serviceLife, unsigned year)
// straight line depreciation method
{
double deprRate = (origVal - scrapVal) / serviceLife;
return origVal - year * deprRate;
}
double DeclineBalance(double origVal, double scrapVal,
unsigned serviceLife, unsigned year)
// declining balance depreciation method
{
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)
// sum of digits depreciation method
{
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))
// calculate the depreciation table
{
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)
// promtp for and obtain double-type number
{
do {
cout << prompt;
cin >> x;
cout << "\n";
} while (x <= 0);
}
void GetUnsigned(const char* prompt, unsigned& n)
// prompt for and obtain unsigned integer
{
do {
cout << prompt;
cin >> n;
cout << "\n";
} while (n < 1);
}
unsigned SelectDeprFunction()
// prompt for and obtain the depreciation function
{
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";
return (n >= 1 && n <= 3) ? n : 1;
}
main()
{
double OrigVal;
double ScrapVal;
unsigned ServiceLife;
double (*DeprFun[3])(double, double, unsigned, unsigned);
unsigned Choice;
char Answer;
DeprFun[0] = StraightLine;
DeprFun[1] = DeclineBalance;
DeprFun[2] = SumOfDigits;
do {
GetDouble("Enter original value: ", OrigVal);
GetDouble("Enter scrap value: ", ScrapVal);
GetUnsigned("Enter service life: ", ServiceLife);
Choice = SelectDeprFunction() - 1;
CalcDeprTable(OrigVal, ScrapVal, ServiceLife, DeprFun[Choice]);
cout << "More calculations ? (Y/N) ";
cin >> Answer;
cout << "\n";
} while (Answer == 'Y' || Answer == 'y');
return 0;
}