2013-09-28 34 views
0

金字塔我想作一個金字塔是這樣的: -我無法輸出C++

____* 
___*_* 
__*___* 
_*_____* 
********* 

對於n = 5。 行不是下劃線,而是空格。

我嘗試: -

#include <iostream.h> 
void main() 
{ int i,k,l,n; 
cin>>n; 
for(i=1; i<=n-1; i++) 
    { 
     for(k=1; k<=i; k++) 
      {if((k==n+i-1)||(k==n-i+1)) 
      cout<<"*"; 
      else 
      cout<<" "; 
      } 
     cout<<"\n"; 
    } 
for(l=1; l<=2*n-1; l++) 
    cout<<"*"; 
} 

但產量當屬: -

__ * 
_* 

注:這是一個渦輪C++程序。

+4

***'int' ***'main()'... – 2013-09-28 09:47:16

回答

1

UPDATE:

有了一些優化,並採取n的行數,而不是基部寬,我們有一些非常簡單:

void drawPyramid(const int &n) { 
    int b=2*n-1; 
    for (int i=b/2; i>=0; i--) { 
     for (int j=0;j<b-i; j++) { 
      if (i==0 || j==i || j==b-i-1) { 
       std::cout<<"*"; 
      } else { 
       std::cout<<" "; 
      } 
     } 
     std::cout<<std::endl; 
    } 
} 

舊的:

這樣做很有趣,但它也適用。我的方法是開始從金字塔可以具有在其端部的最大寬度的計數器,然後劃分問題分成兩個不同的步驟:

  1. 轉到第一邊緣
  2. 轉到第二邊緣

它肯定可以優化,但它會給你的想法:

int drawPyramid(const int &baseWidth, const char &edgeChar, const char &outsideChar, const char &insideChar) { 
    // test if base width allows to have a single char at the top of it 
    if (baseWidth%2==0) { 
     std::cout<<"Error in 'drawPyramid(const int &baseWidth)': Pyramid base width must be an odd number for the top to match"<<std::endl; 
     return 0; 
    } 

    for (int i=baseWidth; i>=0; i-=2) { // the first edge is initially far, then gets closer 
     int j=0; 

     // Go to first edge 
     while (j<i/2) { 
      std::cout<<outsideChar; 
      j++; 
     } 
     std::cout<<edgeChar; 

     if (i==1) { // at the bottom of the pyramid 
      for (int k=0; k<baseWidth-1; k++) { 
       std::cout<<edgeChar; 
      } 
     } else if (i<baseWidth) { // test if there is a second edge to reach 
      // Go to second edge 
      while (j<baseWidth-i/2-2) { 
       std::cout<<insideChar; 
       j++; 
      } 
      std::cout<<edgeChar; 
     } 

     // Done with the current line 
     std::cout<<std::endl; 
    } 

    return 1; 
} 

希望這有助於:)

+0

行不是需要,那些只是空格,也有像我這樣的簡單版本嗎?我不知道那些函數像std ::,basewidth等 – dknight

+0

事實上,當你訪問'cout'時,你隱式地從std這是一個很好的習慣,通過'::'運算符明確地訪問std特性,所以它清楚地表明它是從std而不是在代碼中的其他地方定義的。是的,可能有一個比這更簡單(基於數學)的版本。 –

+0

你知道嗎? – dknight

1

修改你的循環這個和它的作品

for(i=1; i<=n-1; i++) 
{ 
    for(k=1; k<i + n; k++) // greater range than previously to include whole triangle 
     {if((k==n+i-1)||(k==n-i+1)) // == instead of -- 
     cout<<"*"; 
     else 
     cout<<" "; 
     } 
    cout<<"\n"; 
} 
for(l=1; l<=2*n-1; l++) 
+0

對不起,輸出仍然不正確:( – dknight

+0

這很奇怪我的輸出是正確的。你的輸出是什麼? –

+0

___ * __ * __ * _ * ____ * * ______ * ********* – dknight