数字印刷图案

时间:2018-10-30 18:19:59

标签: c++

样本输入:

5(行)

样本输出:

1
11
202
3003
40004

输入格式:

单个整数N,表示模式的行数。 约束:

N <= 1000

我的代码:

#include<iostream>
using namespace std;
int main()
{
    int n;
    cin>>n;//no. of rows
    cout<<"1"<<endl;// printing  as default
    for(int i=1;i<n;i++) // loop for a row
    {

        for(int j=0;j<=i;j++)// loop for printing elements in a row
        {
            if(i>1) //insert zeros when from row having zeros
            {
                if(j==0 || j==i) //condition for printing non-zero number
                    cout<<i; 
                else
                {
                  for(int k=j+1;k<j;k++) //condition for prnting zeros
                    {
                        cout<<"0";//print zero
                    }
                }

            }
            else
                cout<<i; //only gets executed for i=1

        }
        cout<<endl;//printing new line after a row has ended printing
    }
}

///我在代码中做错什么我的输出没有打印零我没有获得所需的模式

3 个答案:

答案 0 :(得分:1)

除了零条件外,您的代码几乎是正确的。如果这是结束条件,即j为0或i然后打印i否则打印0;

#include<iostream>
using namespace std;
int main()
{ 
   int n;
   cin>>n;//no. of rows
   cout<<"1"<<endl;// printing  as default
   for(int i=1;i<n;i++) // loop for a row
   {

    for(int j=0;j<=i;j++)// loop for printing elements in a row
    {
      j==0 || j==i ? cout << i : cout << 0 ;
    }
    cout<<endl;//printing new line after a row has ended printing
 }
}

答案 1 :(得分:1)

for(int i = 1; i < input; ++i){
    std::cout << i;
    for(int j = 1; j < i; ++j){
        std::cout << "0";
    }
    std::cout << i << "\n";
}

说明:

打印i,然后打印与行所在位置一样多的零,即i-1 0,然后再次打印i。

编辑:

由于有人说我没有回答OP的问题。这是您在执行错误的操作。

#include<iostream>
using namespace std;
int main()
{
    int n;
    cin>>n;//no. of rows
    cout<<"1"<<endl;// printing  as default
    for(int i=1;i<n;i++) // loop for a row
    {

        for(int j=0;j<=i;j++)// loop for printing elements in a row
        {
            if(i>1) //insert zeros when from row having zeros
            {
                if(j==0 || j==i) //condition for printing non-zero number
                    cout<<i; 
                else
                {
                   cout << "0"; //remove the for loop and replace with this
                }

            }
            else
                cout<<i; //only gets executed for i=1

        }
        cout<<endl;//printing new line after a row has ended printing
    }
}

我在else块的第26行添加了一条注释,您正在遍历每个迭代。这实际上将0的倍数添加到您的输出中。

答案 2 :(得分:0)

N = int(input())
def NumberPattern(N):
    for m in range(0,N):
        for n in range(1):
            if m == 0:
                print(1,end='')
            else: 
                print(m*(10**m)+m,end='')
        print('')
        
NumberPattern(N)