使用运算符重载查找复利
Find compound interest using operator overloading
我正在编写一段代码,试图使用运算符重载找出简单和复利。
虽然我找到了单利,但我对复利有问题。
#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
值。 P
和R
是未初始化的,因此具有垃圾值,例如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)
{
};
相关文章:
- 参数相关查找和流运算符重载
- 在类设计中查找外部命名空间中的重载运算符
- 重载解析、名称查找和函数指针
- 当其中一个函数未编译时,函数重载查找如何工作?
- 查找运算符重载C++错误
- 仅通过参数查找重载地址
- C++ 重载函数名称查找错误
- 重载函数查找轮廓的实例与参数列表不匹配
- C++ 矢量查找() 重载运算符 - 错误
- 为什么两阶段查找无法选择"交换"的重载版本?
- C++ 没有与参数列表匹配的重载函数"sqrt"实例 - 试图查找结构类型的数字数组是否为完美平方
- 使用运算符重载查找复利
- 通过重载新运算符来查找 MFC C++应用中的内存泄漏
- 查找其 & 运算符重载且私有的对象的地址
- 默认参数与重载 wrt.名称查找
- 稍后定义的重载函数的名称查找
- 为什么编译器在重载时停止名称查找
- 为什么非限定名称查找查找所有重载声明
- 重载函数名查找
- Visual Studio 10 和 GCC 4.5 之间的哪个编译器在运算符重载和参数相关查找方面是正确的