2017-02-15 144 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; 
}