#include "Bond.h" // use the Bond header file
#include <assert.h>
#include <math.h>
// default constructor
bond::bond()
{
Price = 0;
YTM = 0;
}
// since YTM is private, we need to set and get the yield-to-maturity:
void bond::set_YTM(double YTM0)
{
assert(YTM0 >= 0);
YTM = YTM0;
}
double bond::get_YTM()
{
return YTM;
}
// calculate the bond price, given YTM, T, t, C, and P:
double bond::price_calculator()
{
// do the sum:
double sum;
for(int i = 1; i <= T; i++)
{
sum = sum + exp(-(i - t)*YTM);
}
return C*sum + P*exp(-(T - t)*YTM);
}
#include <iostream>
#include "Bond.h"
usingnamespace std;
int main(void)
{
bond bond1; // call the default constructor of a bond
cout << "We will calculate the price of a bond given its YTM." << endl;
/*
cout << "Enter the time to maturity (years) of the bond when issued (T): ";
cin >> bond1.T;
cout << "Enter the current time (t): ";
cin >> bond1.t;
cout << "Enter the coupon payment (C): ";
cin >> bond1.C;
cout << "Enter the principal payment (P): ";
cin >> bond1.P;
cout << "Enter the yield-to-maturity (YTM): ";
double YTM_dummy;
cin >> YTM_dummy;
bond1.set_YTM(YTM_dummy);
*/
bond1.T = 4;
bond1.t = 0.1;
bond1.C = 5;
bond1.P = 100;
bond1.set_YTM(0.05);
cout << "Price is: " << bond1.price_calculator() << endl;
return 0;
}
In main, I am trying 2 ways to send in the variables into the bond1 class. In the first way (which I have commented out), I assign the values through cin's. In the second way, I hard-code them into the class. The second way works. But, I don't understand why the first way does not work (this is the way that I want, though). Any ideas? Thanks!
Oops. Sorry about that. I meant to remove Price from that default constructor. (I basically boiled my code down to the core stuff. I have a bunch of other stuff in my program that I know works, but it isn't necessary for the given issue.)
double bond::price_calculator()
{
// do the sum:
double sum;
for(int i = 1; i <= T; i++)
{
sum = sum + exp(-(i - t)*YTM); //warning: ‘sum’ is used uninitialized in this function
}
return C*sum + P*exp(-(T - t)*YTM);
}