【问题标题】:Simple Triangle/Half Pyramid of natural numbers自然数的简单三角形/半金字塔
【发布时间】:2021-12-30 03:03:21
【问题描述】:

我编写了以下 C++ 代码来显示自然数金字塔

#include <iostream>
using namespace std;
int main()
{
    int i,j,n;
    cout<<"Enter Size:";
    cin>>n;
    for(i=n;i>=1;i--)
    {
    for (j=i;j>0;j--)
    {
        cout<<j;
    }
    cout<<endl;
    
}
 return 0;
}

但是如果我们输入 n=3 这个代码显示

321
32
1

我想把它显示为

123
12
1

【问题讨论】:

    标签: c++ counting


    【解决方案1】:

    您必须更改 j 循环,将其从 i 变为 0,并且您需要将其更改为从 1 变为 1 + 1,将其更改为这个,它应该可以工作:

    for (j=1;j<i+1;j++)
    

    【讨论】:

      【解决方案2】:

      简单地说,反转第二个循环。

      #include <iostream>
      using namespace std;
      int main()
      {
          int i,j,n;
          cout<<"Enter Size:";
          cin>>n;
          for(i=n;i>=1;i--)
          {
              for (j=1;j<=i;j++) {cout << j << '\t';}
              cout<<endl;
          }
      }
      

      注意:\t 选项卡只是为了美观,当循环的数字超过 1 位时,您可以看到:

      Enter Size:10
      1       2       3       4       5       6       7       8       9       10
      1       2       3       4       5       6       7       8       9
      1       2       3       4       5       6       7       8
      1       2       3       4       5       6       7
      1       2       3       4       5       6
      1       2       3       4       5
      1       2       3       4
      1       2       3
      1       2
      1
      

      使用std::setw()可以达到同样的效果。

      另外,请参阅 Why is "using namespace std;" considered bad practice?The importance of proper indentation

      【讨论】:

        【解决方案3】:

        如果你想显示如下: 123 12 1

        使用

            cout<<"Enter Size:";
            cin>>n;
            for(i=1;i<=n;i++)
            {
            for (j=i;j<=n-1;j++)
            {
                cout<<j<<endl;
            }
            cout<<endl;
        

        我从头到尾展示你的情况。

        【讨论】:

          猜你喜欢
          • 2015-07-01
          • 2018-02-17
          • 1970-01-01
          • 1970-01-01
          • 2023-01-26
          • 1970-01-01
          • 1970-01-01
          • 2021-06-18
          • 1970-01-01
          相关资源
          最近更新 更多