c++ - 在 C++ 的 cmd 中显示 Pascal 的三角形

标签 c++ algorithm

<分区>

所以我让这段代码起作用了,因为幸运的是我记得函数原型(prototype)!我对 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;
}

最佳答案

除了使用iomanipsetw之外,还可以在每一行的开头加上一些基于行的空格,得到一个等腰三角形结构

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);
  }
}

关于c++ - 在 C++ 的 cmd 中显示 Pascal 的三角形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20671237/

相关文章:

java - (Java) 快速插入、删除和随机选择的数据结构

python - 通过删除 "middlest"项从数组中删除条目的算法?

algorithm - 选择恰好包含 K 个叶子的子树

algorithm - 优化搜索 - 谁能帮忙计算一下这个算法的复杂度

c++ - 在 iPod Touch 上移植使用 cocos2d c++ 制作的游戏

c++ - OpenFileDialog:打开目录

algorithm - 方阵上的最大和

c++ - 为什么在同一个对象上隐式调用两次析构函数?

c++ - 检查 scanf 格式化而不进行转换

c++ - 如何在 C++ 中提高 int 或 long 的幂