【问题标题】:Creating number pattern (triangle numbers) in c++ with minimum loops用最少的循环在 C++ 中创建数字模式(三角形数字)
【发布时间】:2015-09-07 14:16:43
【问题描述】:

我们被要求做一个三角形编号。 c++ 中的模式与 min。循环。三角形图案如下:

____1_____
___2__3____
__4__5__6__
7__8__9__10

我的代码:

#include <iostream>

using namespace std;
int main() {
    int n=0, r=0, i=0;
    cout << "No. of rows: ";
    cin >> r;

    for( n=1; n<=r; n++) {
        for( i=1; i<=r-n; i++) {
            cout << "  ";
        }
        for( i=(n*(n-1)/2)+1; i<=(n*(n+1)/2); i++ ) {
            if( i<10 )
                cout << " " << i << "  ";
            else
                cout << i << "  ";
        }
        cout << "\n";
    }
    return 0;
}

输出

问题

1) 使用模式生成公式是否明智?例如,为了将 i 的值放在最后一个循环中,我使用模式 1,2,4,7 .. 的公式作为 (n*(n-1)/2) +1。这种方式效率更高吗?什么是迭代方法?什么是可能的递归?

2) 是否可以减少数量。循环?减少变量还是减少循环更好?

谢谢!

【问题讨论】:

  • " 减少变量还是减少循环更好?"配置文件并查看
  • @ChrisBeck 我们如何分析?
  • @TimKrul,当然是使用分析器!例如,您可以使用 gprof。
  • 您可以通过对空格使用 std::string 类来减少循环。查一下(特别是如何创建一串重复字符)。

标签: c++ loops iteration


【解决方案1】:
  1. 它是一个简单的增量数字金字塔,不需要任何特殊公式。公式增加了程序的复杂性,因为涉及到更多的计算。尽量保持代码简单。

最简单的方法是:

int main() {
int num,i=1;
cout<<"Enter Number of Rows";
cin>>num;
 for(int r=1; r<=num; r++)
 {
  for(int space=1; space<=num-r; space++){
    cout<<"  ";
    }
  for(int c=1; c<=r; c++,i++){
   cout<<"  "<<i;
   }
  cout<<"\n";
 }
    return 0;
}

【讨论】:

    【解决方案2】:

    这完全是个人意见,但我认为使用公式确实不会影响效率,因为无论如何您都是一次打印一个元素。所以总时间取决于您输入的长度,即r(r+1)/2。

    我写了这个,它似乎也很好用,尽管这段代码中的逻辑是保持按顺序打印元素并在需要时换行。它仅使用一个内部循环来打印每行开头的空格。这是 Ideone link。

    int r;
    cin>>r;                             //number of rows
    int spaces = r-1, rowcount = 1;
    int curcount = 0;
    
    for(int i=1; i<=(r*(r+1))>>1;i++) {
    
        if(curcount == 0) {
            for(int j=0; j<spaces; j++)
                cout<<" ";
            spaces--;
        }
    
        cout<<(i<10?" ":"")<<i<<" ";
        if(++curcount == rowcount) {
            rowcount++;
            curcount=0;
            cout<<endl;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-09-28
      • 2014-06-10
      • 1970-01-01
      • 2012-07-09
      • 1970-01-01
      • 2022-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多