2016-02-14 61 views
0

我正在編寫一個代碼,它試圖使用運算符重載來找出簡單和複合興趣。使用運算符重載查找複合興趣

雖然我發現了簡單的興趣,但我遇到了複合興趣問題。

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

無論我輸入複合值的值,興趣始終爲零。

回答

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) 
{ 

};