使用运算符重载查找复合兴趣

时间:2016-02-14 07:27:16

标签: c++

我正在编写一个代码,试图使用运算符重载找出简单和复合的兴趣。

虽然我发现了简单的兴趣,但我对复利很感兴趣。

#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;
}

无论我输入什么,化合物的兴趣总是为零。

1 个答案:

答案 0 :(得分:0)

Interest int1中创建对象operator *时,只设置I值。 PR未初始化,因此具有垃圾值,例如1.314e-304。您必须从源中复制值:

Interest operator*(int T)
{
    class Interest int1;
    int1.P = P;
    int1.R = R;
    int1.I= P*R*T;
    return int1;
}

您还应该在默认构造函数中为类成员设置默认值,以避免将来出现错误:

Interest() : P(0.0), R(0.0), I(0.0)
{

};