如何制作柱形图?

CPP*_*ARD -2 c++ column-chart

我在做图表时遇到问题。我希望在同一行中输出图表,而不更改代码,也不使其水平。我希望使用 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<<"\n\nEnter annual interest rate(%): ";
    cin>>interest_rate;
    interest_rate = interest_rate / 100;
    cout<<"\n\nEnter 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<<"Month\tPayment(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;
}
Run Code Online (Sandbox Code Playgroud)

上述代码的输出:

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.
Run Code Online (Sandbox Code Playgroud)

所需的输出:

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.
Run Code Online (Sandbox Code Playgroud)

joh*_*ohn 5

您不需要撤消,endl只需重新组织代码,以便首先按照正确的顺序执行操作,如下所示

void outputStatistics()
{
    cout<<"Month\tPayment(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;
    }
}
Run Code Online (Sandbox Code Playgroud)

此代码一次输出一行,您的代码首先输出一列,然后输出下一列。

  • @CPP_is_no_STANDARD 是的,当然。但解决方案是相同的,您应该以这样的方式编写代码,以便一次可以输出一行数据,并在每行末尾添加一个“endl”。 (3认同)
  • 如果有多个列怎么办?会影响代码吗? (2认同)