在cmd中为c ++制作pascal的三角形

时间:2013-12-19 00:17:37

标签: c++ algorithm

所以我得到了这个代码,因为幸运的是我记得函数原型!我对C ++很陌生。我真的很好奇我将如何将这个变成一个在某处使用空格的实际三角形。我承认我没有孜孜不倦地试图解决这个问题。我只是想找到看起来不像图片但实际的三角形。很多帮助将会受到赞赏。

enter image description here

//

#include "stdafx.h"
#include <iostream>
#include <algorithm>
#include <vector>
#include <iterator>

void genPyrN(int rows) 
{
  if (rows < 0) return;
  // save the last row here
  std::vector<int> last(1, 1);
  std::cout << last[0] << std::endl;

  for (int i = 1; i <= rows; i++) {
    // work on the next row
    std::vector<int> thisRow;
    thisRow.reserve(i+1);
    thisRow.push_back(last.front()); // beginning of row
    std::transform(last.begin(), last.end()-1, last.begin()+1, std::back_inserter(thisRow), std::plus<int>()); // middle of row
    thisRow.push_back(last.back()); // end of row

    for (int j = 0; j <= i; j++)
      std::cout << thisRow[j] << " ";
    std::cout << std::endl;

    last.swap(thisRow);
  }
}

int _tmain(int argc, _TCHAR* argv[])
{
    using namespace std;

    genPyrN(9);
    cin.get();
    cin.get();
    return 0;
}

1 个答案:

答案 0 :(得分:1)

除了使用iomanip&#39; s setw之外,您还可以根据每行开头的行添加一些空格,以获得等腰三角形结构

for (int k = i; k < rows; ++k)
{
  std::cout << "  ";
}

例如,如果您知道您的值将适合三位数:

#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <iterator>

void genPyrN(int rows) 
{
  if (rows < 0) return;
  // save the last row here
  std::vector<int> last(1, 1);
  for (int k = 0; k < rows; ++k)
  {
    std::cout << "  ";
  }
  std::cout << std::setw(3) << last[0] << std::endl;

  for (int i = 1; i <= rows; i++) {
    // work on the next row
    std::vector<int> thisRow;
    thisRow.reserve(i+1);
    thisRow.push_back(last.front()); // beginning of row
    std::transform(last.begin(), last.end()-1, last.begin()+1, std::back_inserter(thisRow), std::plus<int>()); // middle of row
    thisRow.push_back(last.back()); // end of row

    for (int k = i; k < rows; ++k)
    {
      std::cout << "  ";
    }
    for (int j = 0; j <= i; j++)
    {
      std::cout << std::setw(3) << thisRow[j] << " ";
    }
    std::cout << std::endl;

    last.swap(thisRow);
  }
}