如何在C ++中显示此数字模式?

时间:2011-05-09 18:43:21

标签: c++

我必须显示这个数字模式:

-3  1  5  9
7  12  17
15 21

使用:

int number = __________________; // assign correct initial value
int row, col;

for (row = 1; row <= 3; row++)
{
    // adjust number so it displays the correct first value in the row
    ________________________________________________
    for (col = 1; col <= ___5 - row___; col++)
    {
      cout << setw (5) << number;

     // adjust number so it displays the next correct value in this row 
    ______________________number + row + 3;_________________________________ 
        } / /end inner for loop
 cout << endl;
 } // end outer for loop

我知道数字+行+3会得到正确的数字,但我似乎无法获得正确的起始值。

3 个答案:

答案 0 :(得分:0)

试试这个

number = -3

for(row = 1; row <= 3; row++){
   for (col = 0; col < 5 - row; col ++){
       display (number + col * (3 + row));
   }
   number += 12 - row * 2;
}

根据您的限制,即:

int number = 0; // assign correct initial value
int row, col;

for (row = 1; row <= 3; row++)
{
    // adjust number so it displays the correct first value in the row
    number += 12 - (row-1) * 2 - (row+2) * (6 - row);

    for (col = 1; col <= 5 - row; col++)
    {
        cout << setw (5) << number;

        // adjust number so it displays the next correct value in this row 
        number = number + row + 3;
    } / /end inner for loop
    cout << endl;
 } // end outer for loop

说明:

(不是子弹)+ [12 - (row-1)* 2]用于在-3,7和15之间移动

(不是子弹) - [((row-1)+ 2)*(5 - (row - 1))]用于补偿内部循环中数字的增长

由于row = 1的右边部分的结果为-3,因此初始编号为0。

答案 1 :(得分:0)

int number = -1; // assign correct initial value 
int row, col;  
for (row = 1; row <= 3; row++) {     
// adjust number so it displays the correct first value in the row
    number -=2;
    for (col = 1; col <= ___5 - row___; col++){       
        cout << setw (5) << number;       
        // adjust number so it displays the next correct value in this row
        ______________________number + row + 3;
    } / /end inner for loop  
    cout << endl;  
} // end outer for loop

答案 2 :(得分:0)

#include<iostream>
using namespace std;

int main()
{ 
  int i,j; 
  int temp=-3;

  for(i=0;i<3;++i)
  {    
      for(j=0;j<4-i;++j)
      {
          cout<<temp<<" ";
          temp=temp+4+i;
      }

      temp=temp-(4+i);
      temp=temp-2;
      cout<<"\n";
  }

  char dd;
  cin>>dd;
  return 2;
}