编程拼图 - 绘制倒三角形

时间:2015-02-02 13:15:03

标签: c++

最初的问题是用这样的哈希创建一个三角形:

########
 ######
  ####
   ##

我决定将三角形分成两半并创建每个形状的一半。现在我有了创建这个形状的代码:

####
###
##
#

代码:

#include <iostream>
using std::cin;
using std::cout;
using std::endl;

int main () {
    for (int row = 1; row <= 4; row++) {
        for (int hashNum = 1; hashNum <= 5 - row; hashNum++) {
            cout << "#";
        }
        cout << endl;
    }
}

然而,我无法弄清楚如何创建另一半的形状。有没有人有任何想法?

3 个答案:

答案 0 :(得分:1)

当然:将空白区域视为空格的三角形,并将当前三角形的宽度加倍。

答案 1 :(得分:1)

这是一个非常循序渐进的方法。请注意,有更优雅的方法可以做到这一点,即想到递归。

#include <iostream>  

void DrawTriangle(unsigned int rows)
{
    // Loop over the rows
    for(unsigned int spaces = 0; spaces < rows; ++spaces)
    {
        // Add the leading spaces
        for(unsigned int i = 0; i < spaces; ++i)
        {
            std::cout << ' ';
        }
        // Add the hash characters
        for(unsigned int j = 0; j < (rows - spaces)*2; ++j)
        {
            std::cout << '#';
        }
        // Add the trailing spaces
        for(unsigned int i = 0; i < spaces; ++i)
        {
            std::cout << ' ';
        }
        // Add a newline to complete the row
        std::cout << std::endl;
    }
}

int main() {
    DrawTriangle(4);
    return 0;
}

Output

########
 ###### 
  ####  
   ##   

答案 2 :(得分:0)

首先,我会考虑你问题的参数。您正在尝试使用ascii字符绘制n行高度的三角形。考虑到你在下一行的每一行取下一个字符,三角形底边的最小宽度为2 *(n-1)+1。例如,如果你有n = 3:

#####
 ###
  #

这样做你的三角形会更好,底部只有一个'#'。之后,该计划更加直截了当。你可以做这样的事情:

#include <iostream>

using namespace std;

void DrawInvTri(unsigned int nrows)
{
    unsigned int ncols= (nrows-1)*2+1;

    for (int i=0; i<nrows; i++)
    {
        // Write spaces before tri
        for (unsigned int j=0; j<i; j++)
            cout << " ";
        // Write actual tri chars
        for (unsigned int k=i; k<(ncols - i); k++)
            cout << "#";
        // Next line
        cout << endl;
    }

}

int main()
{
    DrawInvTri(5);
    DrawInvTri(3);
    DrawInvTri(4);

    return(0);
}