使用运算符重载查找复利

Find compound interest using operator overloading

本文关键字:查找 重载 运算符      更新时间:2023-10-16

我正在编写一段代码,试图使用运算符重载找出简单和复利。

虽然我找到了单利,但我对复利有问题。

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

无论我输入什么,复利值始终为零。

当您在operator *中创建对象Interest int1时,您只设置了它的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)
{
};