我遇到了这个程序的问题。当我编译它时,我根据用户输入初始化所有变量,但是cout仍然显示问题有' 0' 0对于大多数陈述而言,对于其中一个陈述而言,它是一个负面的陈述'数。有什么想法吗?
#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;
};
答案 0 :(得分:0)
您在这些行上使用默认构造函数:
mPayment m;
tPayment t;
iPayment i;
他们对mort1
中保留的先前输入数据没有概念。你没有注意任何方式分享&#34;分享&#34;或&#34;沟通&#34;这个数据。
m
,t
,i
都是使用随机数据初始化的。与mort1
无关。
我不会详细了解这里的正确架构,但是你应该阅读有关基类初始化的内容。作为一个提示我会在您的(有点奇怪的)示例中说,您可以尝试使这种语法有效:
mPayment m(mort1);
答案 1 :(得分:0)
您正在使用MortgageCalc mort1; mPayment m; tPayment t; iPayment i;
等所有不同的对象。
这些对象没有任何关系。
示例:
mort1 = {term, monthly, total, interest, years, loan}
并假设您已使用1
进行初始化mort1 = {term=1, monthly=1, total=1, interest=1, years=1, loan=1}
但它不会影响m,因为它们都存储在不同位置的内存中。
m = {term=0, monthly=0, total=0, interest=0, years=0, loan=0}
您可以检查两者的基本地址是否为cout<<&mort1<<endl<<&m;
。
您设置的数据成员属于MortgageCalc mort1
而非mPayment m; tPayment t;
。
你需要刷新你的C ++基础知识。