编程难题 - 绘制一个倒三角形

Programming puzzle - drawing an inverted triangle

本文关键字:一个 三角形 难题 绘制 编程      更新时间:2023-10-16

最初的问题是用哈希创建一个三角形,如下所示:

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

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

####
###
##
#

法典:

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

但是,我不知道如何创建形状的另一半。有人有什么想法吗?

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

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

输出

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

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

首先,我会考虑你的问题的参数。您正在尝试使用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);
}