我在做图表时遇到了一个问题。我想在不改变代码的情况下在同一行中输出图表,并且不使其水平。我希望使用for循环来解决这个问题,因为我可以遍历所有元素,因为我有相同的元素。
代码如下:
# include <iostream>
using namespace std;
class InterestCalculator
{
protected:
float principal_amount = 320.8;
float interest_rate = 60.7;
float interest = interest_rate/100 * principal_amount;
public:
void printInterest()
{
cout<<"Principal Amount: RM "<<principal_amount<<endl;
cout<<"Interest Rate(%): "<<interest_rate<<endl;
cout<<"Interest: RM"<<interest<<endl;
}
};
class LoanCalculator : public InterestCalculator
{
private:
int loan_term;
int month;
float month_payment;
public:
void displayVariable()
{
cout<<"Enter loan amount (RM): ";
cin>>principal_amount;
cout<<"nnEnter annual interest rate(%): ";
cin>>interest_rate;
interest_rate = interest_rate / 100;
cout<<"nnEnter loan term in years: ";
cin>>loan_term;
month = loan_term*12;
month_payment = (principal_amount*interest_rate + principal_amount) / month;
cout<<endl<<endl;
}
void outputStatistics()
{
cout<<"MonthtPayment(RM)tPrincipal(RM)tInterest(RM)tBalance(RM)n";
for(int i = 1; i <=month; i++)
{
cout<<i<<endl;
}
for(int j = 0; j <=month; j++)
{
cout<<"t"<<month_payment<<endl;
}
}
};
int main()
{
LoanCalculator obj;
obj.displayVariable();
obj.outputStatistics();
return 0;
}
上述代码的输出:
Enter loan amount (RM): 120
Enter annual interest rate(%): 1.2
Enter loan term in years: 1
Month Payment(RM) Principal(RM) Interest(RM) Balance(RM)
1
2
3
4
5
6
7
8
9
10
11
12
10.12
10.12
10.12
10.12
10.12
10.12
10.12
10.12
10.12
10.12
10.12
10.12
10.12
Process returned 0 (0x0) execution time : 3.940 s
Press any key to continue.
期望输出:
Enter loan amount (RM): 120
Enter annual interest rate(%): 1.2
Enter loan term in years: 1
Month Payment(RM) Principal(RM) Interest(RM) Balance(RM)
1 10.12
2 10.12
3 10.12
4 10.12
5 10.12
6 10.12
7 10.12
8 10.12
9 10.12
10 10.12
11 10.12
12 10.12
Process returned 0 (0x0) execution time : 3.940 s
Press any key to continue.
你不需要撤销endl
,你只需要重新组织你的代码,以便你在正确的顺序做事情,就像这样
void outputStatistics()
{
cout<<"MonthtPayment(RM)tPrincipal(RM)tInterest(RM)tBalance(RM)n";
for(int i = 1; i <=month; i++)
{
// output one row at a time
cout<<i<<"t"<<month_payment<<endl;
}
}
此代码一次输出一行,您的代码先输出一列,后输出下一列。
另一个选择是使用setw操纵符,但更好的选择是对这个基于列的图表使用t。
setw
更灵活,因为你可以改变空格数.
但t
将间隔4个空格每次使用它,这就是为什么我提到t是为这个基于列的图表。