简体   繁体   English

如何制作这个数字形状?

[英]how to make this number shape?

Write a program to display the below pattern with n rows, where n is in the range between 1 and 100. The variable n should be entered by the user.编写一个程序来显示下面的 n 行模式,其中 n 的范围在 1 到 100 之间。变量 n 应该由用户输入。 If the user input is between 1 and 100 then output the pyramid as given below, otherwise prompt the user to enter n again.如果用户输入在 1 到 100 之间,则 output 金字塔如下所示,否则提示用户再次输入 n。

Here is the sample output: Enter the number of rows: 6这是示例 output: 输入行数:6

1 1

2 3 2 3

3 4 5 3 4 5

4 5 6 7 4 5 6 7

5 6 7 8 9 5 6 7 8 9

6 7 8 9 10 11 6 7 8 9 10 11

( enter image description here ) 在此处输入图片描述

this is my code it shows a close answer but not correct.这是我的代码,它显示了一个接近的答案,但不正确。

 int num=1  ,  counter=1;
   cout << "Enter the number of rows: " ;
   cin>>num;

       for(int i=0;i<=num;i++)
       {
           for(int j=0;j<=i;j++)
           {
               cout<<counter<<" ";
               counter++;
           }
           cout<<endl;
       }
int num = 1, counter = 1, temp = 1;
cout << "Enter the number of rows: ";
cin >> num;

for (int i = 0; i < num; i++)
{
    for (int j = 0; j <= i; j++)
    {
        cout << temp << " ";
        temp++;
    }
    counter++;
    temp = counter;
    cout << endl;
}

The variable temp serves as a counter for the rows, meanwhile the variable counter is responsible for the starter numbers in the first column.变量 temp 用作行的计数器,同时变量 counter 负责第一列中的起始编号。

you should either set counter in each run of outer loop, right before entering the inner one with something like counter = i+1 , the way you wrote this code value of this variable carries over to the next iteration and keeps going only upwards.您应该在每次运行外部循环中设置counter ,就在进入内部循环之前使用counter = i+1之类的东西,您编写此变量的此代码值的方式将延续到下一次迭代并继续向上。

Alternate solution would be to print j instead and work on inner loop, it should then start with i and the first number that wouldn't qualify would be 2*i this way for i equal 2 the sequence would be 2 3 ,另一种解决方案是打印j并在内部循环上工作,然后它应该以i开头,第一个不合格的数字将是2*i这样i等于2序列将是2 3

either way you should also rework your outer loop, as right now it starts with 0 and ends with num meaning it goes through num+1 iterations无论哪种方式,您还应该重新设计您的外部循环,因为现在它以 0 开始并以num结束,这意味着它经历了num+1次迭代

int rows, i, j = 0, number = 0, counter = 0;
cout << "Enter the number of rows: ";
cin >> rows;

for (i = 1; i <= rows; i++)
{
  while (j != 1 * i)
  {
    if (counter <= rows)
    {
      cout << i+j << " ";
      counter++;
    }
   ++j;
  }
number=counter=j=0;
cout << endl;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM