Find compound interest using operator overloading - c++

I am writing a code that tries to find out the simple and compound interest using operator overloading.
While I have found the simple interest, I am having problem with the compound interest.
#include<iostream>
#include<iomanip>
using namespace std;
class Interest
{
private:
double P;
double R;
double I;
public:
Interest(){};
~Interest(){};
void setP(double recieveP){P = recieveP;}
void setR(double recieveR){R = recieveR/100;}
double getP(){return P;}
double getI(){return I;}
Interest operator*(int T)
{
class Interest int1;
int1.I= P*R*T;
return int1;
}
};
int main()
{
class Interest simp1;
class Interest comp1;
double Principle,Rate,Years;
cout << "Enter the Principle Amount" << endl;
cin >> Principle;
simp1.setP(Principle);
comp1.setP(Principle);
cout << "Enter the Rate Amount" << endl;
cin >> Rate;
simp1.setR(Rate);
comp1.setR(Rate);
cout << "Enter the number of years:";
cin >> Years;
simp1 = simp1*Years;
cout << "The Simple Interest is: " << simp1.getI() << endl;
for(int i =0; i < Years; i++)
{
comp1 = comp1*1;
comp1.setP(comp1.getI()+comp1.getP());
}
cout << "The compound Interest is: " << comp1.getI() << endl;
return 0;
}
No matter what I enter the values for the compound Interest is always zero.

When you create object Interest int1 in operator *, you set only it's I value. P and R are uninitialized, so the have trash value, like 1.314e-304. You must copy values from the source:
Interest operator*(int T)
{
class Interest int1;
int1.P = P;
int1.R = R;
int1.I= P*R*T;
return int1;
}
You also should set default values for your class members in default constructor, to avoid future mistakes:
Interest() : P(0.0), R(0.0), I(0.0)
{
};

Related

Issues with retrieving information from a class module for output within a switch statement

I know this may be something obvious to some with experience but I am in the middle of my first real class for C++ programming. I have come across something in my code that I have been trying to resolve without any success. I am trying to extract the sum of the total value of "m_cost" stored within a array that is inside of these class modules. I want to output the total value inside of a switch statement for print out. Just seeing if someone can point me in the right direction or if I have completely gone off-track with the logic.
Project Code section in question:
void materialsMenu()
{
Inventory record[MAX_REC];
int i, n;
cout << "\n=====Inventory Management=====\n";
cout << "\nHow many Materials are there to be used? : ";
cin >> n;
cout << "Enter " << n << " Materials\n";
for (i = 0; i < n; i++)
record[i].getdata();
cout << "\n\n---Material Information---\n";
cout << "\n" << setw(8) << "Item Name "
<< setw(10) << " Price per foot "
<< setw(19) << " Cost " << endl;
cout << endl << "-------------------------------------------" << endl;
for (i = 0; i < n; i++)
record[i].showdata();
}
void Inventory::getdata() {
cout << endl;
cout << "\nEnter Material Name : ";
cin >> itemName;
cout << "Enter Price Per Foot : ";
cin >> ppf;
cout << "Enter Total Length Needed in Feet (ft) : ";
cin >> length;
cout << endl;
m_cost = ppf*length;
m_costT=???????? **this is the issue**
}
Materials.H file contents:
#ifndef MATERIALS_H
using namespace std;
class Materials {
private:
char itemName[15];
float ppf;
float length;
double m_cost;
float m_costT;
public:
Materials()
{
ppf = 0;
length = 0;
m_cost = 0;
m_costT = 0;
}
Materials(int itemName, float ppf, float length, double m_cost, float
m_costT)
{
length = getLength();
ppf = getPpf();
m_cost = getCost();
m_costT = getTotal();
}
float getLength()
{
return length;
}
float getPpf()
{
return ppf;
}
double getCost()
{
return m_cost;
}
float getTotal()
{
return m_costT;
}
void getdata();
void showdata();
};
#endif // !MATERIALS_H
Consider something like this to hold your records. It's very simple, but it demonstrates the idea of one class holding another and shows information hiding and all sorts of other tidbits. You are struggling to get that total because the Record class shouldn't care about this. The total is a concept outside of the scope of a Record. And as such, it is very difficult to calculate this from where you wanted to do it. (Though it is possible, it breaks all sorts of C++ rules and should be avoided)
Example:
class Record;
class RecordHolder
{
public:
int GetTotal()
{
int retVal = 0;
for(int i=0; i<10; i++) // Magic number 10 for demo purposes only...
{
retVal += records[i].m_cost; // Or use a public get function.
}
return retVal;
}
private:
Record records[10]; // Magic number 10 for demo purposes only...
};
The RecordHolder could also do printing, add/removing records, etc. It controls the records array. The Records are just Records and don't care about such management.

initialize class functions but output still 0

I am having problems with this program. When I compile it, I intialize all of the variables based upon the users input, but the cout still shows that the problem has '0' for most of the statements and for one of the statements its a '-negative' number. Any thoughts?
#include <iostream>
#include <conio.h>
#include <cmath>
#include <stdexcept>
using namespace std;
class MortgageCalc
{
protected:
float term;
public:
void setData(float, float, float);
float setTerm ();
float monthly;
float total;
float interest;
int years;
float loan;
};
void MortgageCalc::setData(float l, float i, float y)
{
loan = l;
interest = i;
years = y;
setTerm();
}
float MortgageCalc::setTerm()
{ //simple interest calculation with power calc to establish whole number translation
term = pow((1 + ((interest/100) / 12)), (12 * years));
return term;
}
class mPayment : public MortgageCalc
{
public:
int monthly()
{
return ((loan * ((interest/100) / 12) * term ) / (term - 1));
}
};
class tPayment : public mPayment
{
public:
int total()
{
return (monthly() * (years * 12));
}
};
class iPayment : public tPayment
{
public:
int plusInterest()
{
return (total() - loan);
}
};
int main()
{
double loan(0), interest(0);
int years = 0;
MortgageCalc mort1;
cout << "Enter the total loan amount on your mortgage loan: $"; //established loan variable
cin >> loan;
cout << "Enter the interest rate (in whole #'s only): "; //establishes interest rate variable
cin >> interest;
cout << "Enter the length of the loan in years: "; //establishes term of payments
cin >> years;
mort1.setData(loan, interest, years);
mPayment m;
cout << "Monthly payment due is " << m.monthly() << "." << endl;
tPayment t;
cout << "Total payment will be " << t.total() << "." << endl;
iPayment i;
cout << "Total payment plus Interest will be " << i.plusInterest() << "." << endl;
return 0;
};
You are taking all different objects like MortgageCalc mort1; mPayment m; tPayment t; iPayment i;.
These object do not have any relation.
Example:
mort1 = {term, monthly, total, interest, years, loan}
and suppose you have initialize with 1
mort1 = {term=1, monthly=1, total=1, interest=1, years=1, loan=1}
but it doesnot impact to the m because both are stored in memory on different location.
m = {term=0, monthly=0, total=0, interest=0, years=0, loan=0}
You can check both have different base address like cout<<&mort1<<endl<<&m; .
Data member you have set is part of MortgageCalc mort1 instead of mPayment m; tPayment t;.
You need to brush up your C++ basic's.
You use default constructors on those lines:
mPayment m;
tPayment t;
iPayment i;
They have no notion of previously input data held in mort1. You did not take care for any way to "share" or "communicate" this data.
m,t,i were all initialized with random data. There is no relation to mort1.
I won't go into details of what correct architecture here would be, but you should read about base class initialization. As a hint I'd say in your (a little weird) example you could try making this syntax work:
mPayment m(mort1);

no candidates for error compile error

I am trying to compile my application and it keeps running into "no match for 'operator<<'... it is not clear what the exact error of the program seems to be because he object is configured correctly as far as I can see.
#include <iostream>
#include <conio.h>
#include <cmath>
#include <stdexcept>
using namespace std;
class MortgageCalc
{
protected:
float term;
public:
void setData(float, float, float);
float setTerm ();
float monthly;
float total;
float interest;
float setLoan(void); //mutator
float setIntrest(void); //mutator
float setYears(void);
int years;
float loan;
};
void MortgageCalc::setData(float l, float i, float y)
{
loan = l;
interest = i;
years = y;
setTerm();
}
float MortgageCalc::setTerm()
{ //simple interest calculation with power calc to establish whole number translation
term = pow((1 + ((interest/100) / 12)), (12 * years));
return term;
}
float MortgageCalc::setLoan(void)
{ //returns loan amt to private member
return loan;
}
float MortgageCalc::setIntrest(void)
{ //returns interest amt to private member
return interest;
}
float MortgageCalc::setYears(void)
{ //returns years to private member
return years;
}
class mPayment : public MortgageCalc
{
public:
int monthly()
{
return ((loan * ((interest/100) / 12) * term ) / (term - 1));
}
};
class tPayment : public mPayment
{
public:
int total()
{
return (monthly() * (years * 12));
}
};
class iPayment : public tPayment
{
public:
int plusInterest()
{
return (total() - loan);
}
};
int main()
{
double loan(0), interest(0);
int years = 0;
MortgageCalc mort1;
cout << "Enter the total loan amount on your mortgage loan: $"; //established loan variable
cin >> loan;
cout << "Enter the interest rate (in whole #'s only): "; //establishes interest rate variable
cin >> interest;
cout << "Enter the length of the loan in years: "; //establishes term of payments
cin >> years;
mort1.setData(loan, interest, years);
mPayment m;
cout << "Monthly payment due is " << m.monthly() << "." << endl;
tPayment t;
cout << "Total payment will be " << t.total() << "." << endl;
iPayment i;
cout << "Total payment plus Interest will be " << i.plusInterest() << "." << endl;
return 0;
};
cout << "Total payment plus Interest will be " << i.plusInterest << "." << endl;
plusInterest is a class method pointer. Unsurprisingly, std::ostream has no clue what to do with a class method pointer, and is rightfully voicing its very strong objection, to such a preposterous proposition that it knows what to do with some strange class's method pointer.
You probably meant to write:
cout << "Total payment plus Interest will be " << i.plusInterest() << "." << endl;
Now, that's a proper function call, that returns an int, and std::ostream is now delighted to take this int, and do its magic with it.

C++ Array outputting address?

I posted earlier for the first time and was able to almost complete this assignment. The program isn't giving an error, but I'm getting undesired results. The output appears to be outputting the array address instead of the data I input. Or at least I think it is based on my very very limited knowledge. Can anyone help guide me in how to fix this? I've been working on this all day and at this hour, I think I'm ready to throw in the towel. Any advice is greatly appreciated, thanks!
// Amanda
// SoccerPlayer.cpp : main project file.
// October 6, 2012
/* a. Design a SoccerPlayer class that includes three integer fields: a player's jersey number,
number of goals, and number of assists. Overload extraction and insertion operators for the class.
b. Include an operation>() function for the class. One SoccerPlayer is considered greater
than another if the sum of goals plus assists is greater.
c. Create an array of 11 SoccerPlayers, then use the > operator to find the player who has the
greatest goals plus assists.*/
#include "stdafx.h"
#include<conio.h>
#include<iostream>
#include<string>
using namespace std;
class SoccerPlayer
{
friend std::ostream& operator<<(std::ostream&, const SoccerPlayer&);
friend istream& operator>>(istream&, SoccerPlayer&);
private:
int jerseyNum;
int numGoals;
int numAssists;
public:
SoccerPlayer(int, int, int);
int score;
int operator>(SoccerPlayer&);
void DisplayStar();
};
SoccerPlayer::SoccerPlayer(int jersey = 0, int goal = 0, int assist = 0)
{
jerseyNum = jersey;
numGoals = goal;
numAssists = assist;
}
void SoccerPlayer::DisplayStar()
{
cout<<"Player Number: "<< jerseyNum <<endl;
cout<<"Goals Scored: "<< numGoals <<endl;
cout<<"Assists Made: "<< numAssists <<endl;
}
std::ostream& operator<<(std::ostream& player, const SoccerPlayer& aPlayer)
{
player << "Jersey #" << aPlayer.jerseyNum <<
" Number of Goals " << aPlayer.numGoals <<
" Number of Assists " << aPlayer.numAssists;
return player;
}
std::istream& operator>>(std::istream& inPlayer, SoccerPlayer& aPlayer)
{
cout << "Please enter the jersey number: ";
inPlayer >> aPlayer.jerseyNum;
cout << "Please enter the number of goals: ";
inPlayer >> aPlayer.numGoals;
cout << "Please enter the number of assists: ";
inPlayer >> aPlayer.numAssists;
aPlayer.score=(aPlayer.numGoals) + (aPlayer.numAssists);
return inPlayer;
}
int SoccerPlayer::operator>(SoccerPlayer& aPlayer)
{
int total = 0;
if (score > aPlayer.score)
total = 1;
return total;
}
int main()
{
const int sz = 11;
int x;
SoccerPlayer aPlayer[sz];
for(x = 0; x < sz; ++x)
cin >> aPlayer[x];
{
double max = aPlayer[x].score;
for(int i = 1; i<sz; ++i)
{
if(aPlayer[i] > aPlayer[x])
{
max=aPlayer[i].score;
}
}
cout << max << endl;
cout << aPlayer[x];
}
_getch();
return 0;
}
It looks as if you intended a loop here, but it's malformed:
for(x = 0; x < sz; ++x)
cin >> aPlayer[x];
{
double max = aPlayer[x].score;
for(int i = 1; i<sz; ++i)
{
if(aPlayer[i] > aPlayer[x])
{
max=aPlayer[i].score;
}
}
cout << max << endl;
cout << aPlayer[x];
}
You meant (I think) that double max ... should be inside the loop, but the cin >> ... line comes after the for statement, outside the braces. So the iteration applies only to the cin >> ... statement; once it's done, control proceeds to double max = aPlayer[x].score;, but x (left over from for(...)) is equal to sz, so aPlayer[x] is outside the array, in no-man's-land.
Put the cin >> ... inside the brackets.
The problem is that you only print the element aPlayer[x]. But notice that your first for loop terminates when x = 11. Well, that's one past the end of the array, so really, you're outputting junk.
I just tried it out with aPlayer[0] instead and got expected results.
This is what I ended up with. Thanks everyone for the help!
// Amanda
// SoccerPlayer.cpp : main project file.
// October 6, 2012
/* a. Design a SoccerPlayer class that includes three integer fields: a player's jersey number,
number of goals, and number of assists. Overload extraction and insertion operators for the class.
b. Include an operation>() function for the class. One SoccerPlayer is considered greater
than another if the sum of goals plus assists is greater.
c. Create an array of 11 SoccerPlayers, then use the > operator to find the player who has the
greatest goals plus assists.*/
#include "stdafx.h"
#include<conio.h>
#include<iostream>
#include<string>
using namespace std;
//soccer player class - see above description
class SoccerPlayer
{
friend std::ostream& operator<<(std::ostream&, const SoccerPlayer&);
friend istream& operator>>(istream&, SoccerPlayer&);
private:
int jerseyNum;
int numGoals;
int numAssists;
public:
SoccerPlayer(int, int, int);
int score;
int operator>(SoccerPlayer&);
void DisplayStar();
};
//soccerplayer constructor
SoccerPlayer::SoccerPlayer(int jersey = 0, int goal = 0, int assist = 0)
{
jerseyNum = jersey;
numGoals = goal;
numAssists = assist;
}
//to display star player
void SoccerPlayer::DisplayStar()
{
cout<<"Jersey #: "<< jerseyNum <<endl;
cout<<"Goals Scored: "<< numGoals <<endl;
cout<<"Assists Made: "<< numAssists <<endl;
}
//overload operator out
std::ostream& operator<<(std::ostream& player, const SoccerPlayer& aPlayer)
{
player << "Jersey #" << aPlayer.jerseyNum <<
" Number of Goals " << aPlayer.numGoals <<
" Number of Assists " << aPlayer.numAssists;
return player;
}
//overload operator in
std::istream& operator>>(std::istream& inPlayer, SoccerPlayer& aPlayer)
{
cout << "Please enter the jersey number: ";
inPlayer >> aPlayer.jerseyNum;
cout << "Please enter the number of goals: ";
inPlayer >> aPlayer.numGoals;
cout << "Please enter the number of assists: ";
inPlayer >> aPlayer.numAssists;
aPlayer.score=(aPlayer.numGoals) + (aPlayer.numAssists);
return inPlayer;
}
//overload operator greater than
int SoccerPlayer::operator>(SoccerPlayer& aPlayer)
{
int total = 0;
if (score > aPlayer.score)
total = 1;
return total;
}
//main declaration
int main()
{
//11 players
const int sz = 11;
int x;
SoccerPlayer aPlayer[sz];
double max = 0;
//to display star
SoccerPlayer Star;
//allow user to input players, show what they input
for(x = 0; x < sz; ++x)
{
cin >> aPlayer[x];
cout << aPlayer[x] << endl << endl;
for(int i=1; i<sz; i++)
{
Star=aPlayer[0];
if(aPlayer[i] > aPlayer[i+1])
Star=aPlayer[i];
}
}
//show star player
cout << "The Star Player: "<< endl;
Star.DisplayStar();
_getch();
return 0;
}

Addition and subtraction of complex numbers using class in C++

I have here a code that is supposed to ask the user two sets of real and imaginary numbers.
#include <iostream>
using namespace std;
class Complex {
public:
double r;
double i;
public:
Complex();
void add(Complex, Complex);
void subtract(Complex, Complex);
void print();
};
Complex::Complex() {
r = i = 0;
}
void Complex::add (Complex op1, Complex op2) {
r = op1.r+op2.r;
i = op1.i+op2.i;
}
void Complex::subtract (Complex op1, Complex op2) {
r = op1.r-op2.r;
i = op1.i-op2.i;
}
void Complex::print () {
cout << r << i;
}
int main () {
Complex operand1, operand2, result;
cout << "Input real part for operand one: " << endl;
cin >> operand1.r;
cout << "Input imaginary part for operand one: " << endl;
cin >> operand1.i;
cout << "Input real part for operand two: " << endl;
cin >> operand2.r;
cout << "Input imaginary part for operand two: " << endl;
cin >> operand2.i;
result.add(operand1, operand2);
cout << "The sum is " << result.add << endl;
result.subtract(operand1, operand2);
cout << "The difference is " << result.subtract << endl;
}
However, when I compiled the program, lots of errors are displayed (std::basic_ostream) which I don't even get.
Another issue I'm having is in the function void::Complex print. There should be a condition inside cout itself. No if-else. But I have no idea what to do.
The program must run like this:
Input real part for operand one: 5
Input imaginary part for operand one: 2 (the i for imaginary shouldn't be written)
Input real part for operand two: 8
Input imaginary part for operand two: 1 (again, i shouldn't be entered)
/then it will print the input(ed) numbers/
(5, 2i) //this time with an i
(8, 1i)
/then the answers/
The sum is 13+3i.
The difference is -3, 1i. //or -3, i
Please help me! I'm new in C++ and here in stackoverflow and your help would be very appreciated. Thank you very much!
The line
cout << "The sum is " << result.add << endl;
is incorrect, as add is a method so result.add will be a pointer to that method, and cout does not know how to handle it - which makes the compiler spit it out.
Change the line to
cout << "The sum is ";
result.print();
cout << endl;
You need to do the same for the line
cout << "The difference is " << result.subtract << endl;
As to coding style, the two methods are overwrting an existing complex number. Perhaps having a the function like this would be better
Complex &Complex::add (const Complex &op) {
r += op.r;
i += op.i;
return *this;
}
This will enable you to chain additions together and also just add a complex number to the existing complex number.
In addition you could make the class variables r and i private. This will require an alternative constructor:
Complex:Complex(double real, double imaginary) : r(real), i(imaginary) {};
Finally you may wish to consider operator overloading - I am sure you can google that to find a reasonable tutorial.
In main, after you call result.add, you put the same function in the cout stream when it doesn't return anything. I think you meant to write cout << "the sum is " << result.print();
You are already using the std:: namespace. Just use the complex number library in it like this answer suggests: Addition of complex numbers using classes
#include <iostream>
using namespace std;
class Complex {
public:
double r;
double i;
public:
void add(Complex, Complex);
void subtract(Complex, Complex);
void print();
};
void Complex::add (Complex op1, Complex op2) {
r = op1.r + op2.r;
i = op1.i + op2.i;
}
void Complex::subtract (Complex op1, Complex op2) {
r = op1.r - op2.r;
i = op1.i - op2.i;
}
void Complex::print () {
cout << "("<<r<<", " << i <<")";
}
int main () {
Complex operand1, operand2, result;
cout << "\nInput real part for operand one: " << endl;
cin >> operand1.r;
cout << "Input imaginary part for operand one: " << endl;
cin >> operand1.i;
cout << "Input real part for operand two: " << endl;
cin >> operand2.r;
cout << "Input imaginary part for operand two: " << endl;
cin >> operand2.i;
cout << "\nThe sum is ";
result.add(operand1, operand2);
result.print();
cout << "\nThe difference is ";
result.subtract(operand1, operand2);
result.print();
}