【问题标题】:Printing triangle of numbers in C++ in a specific way?以特定方式在 C++ 中打印数字三角形?
【发布时间】:2018-01-26 18:45:33
【问题描述】:

我有一个程序,我必须以特定方式打印数字三角形。例如,我的程序打印以下 5 个:

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

我想用以下方式打印它们:

         1
       1 2
     1 2 3
   1 2 3 4
 1 2 3 4 5

我尝试使用 iomanip 库使用 setw(),但它不起作用。我的问题是如何解决这个问题。

#include <iostream>
using namespace std;
int n,br=1;
int main()
{
    cin>>n;
    while (br<=n)
    {
        for(int i=1; i<=br; i++)
        {

            cout<<i<<' ';
        }
        br++;
        cout<<endl;
    }
    return 0;
}

【问题讨论】:

  • "int n,br=1;" - 为什么作为全局变量?尽可能避免全局变量(在这里你可以轻松可以避免它们)。
  • These manipulators 可能会有所帮助。了解如何将它们与 std::setw 一起使用。实验。

标签: c++ loops printing


【解决方案1】:

您可以在数字输出循环之前添加嵌套在 while 中的 for 循环。然后这个循环可以输出一些空格。

我不会给你代码让你自己做一些工作,但是如果你遇到问题,拿一张纸写下每行应该有多少空格。看看你是否能找到数字的模式或公式,然后代码应该会更容易。

【讨论】:

    【解决方案2】:

    试试这个代码! 另外我附上了代码的输出。

    #include <iostream>
    
    using namespace std;
    
    int main() {
        int count=1;
        int flag=0;
        for(int i=1;i<=5;i++)
        {
            for(int j=5;j>0;j--)
            {
                if(i==j)
                {
                    flag=1;
                }
                if(flag==1)
                {
                    cout<<"\t"<<count;
                    count++;
                }
                else
                {
    
                    cout<<"\t";
                }
    
            }
            flag=0;
            count=1;
            cout<<"\n";
        }
    
    
    }
    

    【讨论】:

      【解决方案3】:

      您可以尝试在 i 循环下方的空间循环。

      for(int j=1;j<=n-br;j++)
          cout<<"  ";
      

      随着 br 的值不断增加,这应该会线性减少空间。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-10-03
        • 2014-04-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多