2017-02-15 69 views
-2

我的输出应该是四个三角形和一个金字塔。我设法得到了四个三角形,但无法弄清金字塔。任何帮助都会很棒。 (我也必须使用setw和setfill)。使用setw建立一个金字塔

输出是左对齐的三角形,然后左对齐倒置。 右对齐三角形,然后右对齐三角形倒置。

这是我的电流输出:

enter image description here

#include <iostream> 
#include <iomanip> 

using namespace std; 

//setw(length) 
//setfill(char) 

int height;  //Number of height. 
int i; 
int main() 
{ 

    cout << "Enter height: "; 
    cin >> height; 

    //upside down triangle 
    for (int i=height; i>=1; i--){ //Start with given height and decrement until 1 
      cout << setfill ('*') << setw((i)) <<"*"; 
      cout << "\n"; 
    }  

    cout<< "\n"; //line break between 

    //rightside up triangle 
    for (int i=1; i<=height; i++){ //Start with 1 and increment until given height 
     cout << setfill ('*') << setw((i)) <<"*"; 
     cout << "\n"; 
    } 

    cout<< "\n"; 

    //right aligned triangle 
    for (int i=1; i<=height; i++){ //Start with 1 and increment until given height 
     cout << setfill (' ') << setw(i-height) << " "; 
     cout << setfill ('*') << setw((i)) <<"*"; 
     cout << "\n"; 
    } 

    cout<< "\n"; 

    //upside down/ right aligned triangle 
    for (int i=height; i>=1; i--){ //Start with given height and decrement until 1 
     cout << setfill (' ') << setw(height-i+1) << " "; 
     cout << setfill ('*') << setw((i)) <<"*"; 
     cout << "\n"; 
    } 

    cout<< "\n"; 
    //PYRAMID 
    for (int i=1; i<=height; i++){ //Start with 1 and increment until given height 
     cout << setfill (' ') << setw(height-i*3) << " "; //last " " is space between 
     cout << setfill ('*') << setw((i)) <<"*"; 
     cout << "\n"; 
     } 
}//end of main 
+0

它很难理解你想要什么显示图像图 –

+0

感谢您的建议。我已添加目前的输出。最后一个三角形应该是金字塔。 – Ace

回答

0

setfill('*')呼叫将否决调用setfill(' ')上一行时,您绘制的金字塔。 每行只能有一个填充字符集。

你可以尝试用“手”“画”中的星号,这样的:

for (int i = 1; i <= height; i++) { 
    cout << setfill (' ') << setw(height - ((i - 1) * 2 + 1)/2); 
    for (int j = 0; j < (i - 1) * 2 + 1; j++) 
     cout << '*'; 
    cout << "\n"; 
} 
0

它始终是最好的,你开始思考如何实现之前确定你所需要的输出。 假设你需要一个高度为5的金字塔,如你的例子。 这意味着最上一行将有一个*。 在完美的世界中,第二排有两个,但在屏幕上很难实现。那么也许它可以有3. 在这种情况下,高度5的最终结果将是:1,3,5,7和9 *。 (我试图在这里绘制,但没有成功,我建议你在任何文本编辑器中绘制它以帮助可视化最终结果)。

现在考虑实施: 请注意,在*之前填充空白的数量至关重要。之后的空白将自行发生。 *之前应该显示多少空白? 如果您尝试在文本编辑器中绘制金字塔,您会意识到它取决于底行的宽度和每个特定行中*的数量。 另外,如果你仔细观察的空白形成一个三角形...

添加: 只是为了让你知道 - 你原来的做法也将工作,如果你会选择通过增加每个后续行*数量2而不是一个。

int BottomRowWidth = 1 + 2 * (height - 1); 
int BlankNumber = (BottomRowWidth - 1)/2; 
int row, width; 
for (row = 1, width =1; (row <= height); row++, width = width+2, BlankNumber--) 
{ 
    if (BlankNumber > 0) 
    { 
     cout << setfill(' ') << setw(BlankNumber) << " "; 
    } 
    cout << setfill('*') << setw(width) << "*"; 
    cout << endl; 
}