编程难题 - 绘制一个倒三角形
Programming puzzle - drawing an inverted triangle
最初的问题是用哈希创建一个三角形,如下所示:
########
######
####
##
我决定将三角形分成两半,并创建每个形状的一半。现在我有创建这个形状的代码:
####
###
##
#
法典:
#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);
}
相关文章:
- 为我的 c++ 类介绍制作一个三角形分类器.我有几个问题
- 以C++输出一个数字三角形
- 形成一个斐波那契三角形,使得每个数字是上面左对角线或右对角线上两个数字的总和
- 给定一个用三角形镶嵌的补丁,如何修改其新的顶点位置
- 使用 C++ 库 GLEW 在 openGl 中绘制一个红色三角形
- 创建一个绿色三角形C Directx
- 创建一个程序以输出三角形平方数的4个
- 在OpenGL中打印一个红色三角形
- 如何打印一个不相等的三角形
- 我如何对此代码进行添加以使用我的 arduino 打印一个完整的三角形
- Direct3D:尝试绘制一个三角形,但什么也没显示
- 如何在 Qwidget 的中心设计一个三角形(在 QT 中使用 OpenGl)
- 输出一个三角形
- Qt和OpenGL,如果我使用属性,可以画一个三角形
- 在我点击的地方画一个三角形
- 用point类写一个三角形类
- GL VBO问题:第一个和最后一个三角形带没有正确显示
- 融合一个三角形循环并行化,计算子指标
- 用C++做一个三角形
- 加上另一个三角形