2013-12-19 42 views
0

所以我得到了这段代码,因为幸运的是我记得函数原型!我对C++很陌生。我真的很好奇,我怎么会把这个转变成一个实际的三角形,在某个地方使用空格。我承认我并没有孜孜不倦地试图解决这个问题。我只是想找到它不像图片,,但一个实际的三角形。很多帮助,将不胜感激。制作pascal的三角形在cmd中显示为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

除了使用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); 
    } 
}