2013-12-23 146 views
-2

我一直在使用嵌套循环创建自己的C++程序来创建某种形状。我最近的项目是建立一个形状,看起来像这样C++嵌套循环形状

* 
** 
*** 
**** 
***** 
    ***** 
    **** 
    *** 
     ** 
     * 

,但我已经写了一个程序,它给我的这个

* 
** 
*** 
**** 
***** 
***** 
**** 
*** 
** 
* 

也在这里结果是我的代码

#include <iostream> 
using namespace std; 

void main(){ 
//displays a top triangle going from 1 - 5(*) 
for (int i = 0; i <= 5; i++){ 
    for (int j = 0; j <= i; j++){ 
     cout << "*"; 

    } 

    cout << endl; 
} 
//displays a bottom to top triangle 5 - 1(*) 
for (int k = 0; k <= 5; k++){ 
    for (int l = 5; l >= k; l--){ 
     cout << "*"; 
    } 

    cout << endl; 
} 
system("pause"); 
} 

这将是有益的谢谢你:)

+1

我会建议之一:在调试器中运行您的程序,看什么,直到你看到不正确的输出发生和/或运行使用你的程序“每次通过每个回路发生铅笔和纸“,再次注意到输出开始看起来错误时,在那一点上注意循环在做什么,为什么它是错误的。 – Eric

+1

我认为这很有趣,你建议有人不知道如何使这个程序工作只是加载'gdb'并得到黑客攻击。 –

回答

1

在你的第二个嵌套循环,你不打印空格。

有一个字符串,是一个三个空格,然后是内循环的每次运行后,追加到它的另一个空间和打印:

spc = " "; 
for (int k = 0; k <= 5; k++){ 
    cout << spc; 
    for (int l = 5; l >= k; l--){ 
     cout << "*"; 
    } 
    spc += " "; 
    cout << endl; 
} 
+0

你也可以告诉我你添加的代码对这个程序做了什么,以及我的错误在哪里。 – user3126681

+0

男人,这是相当自我记录。你还需要''spc'之前的类型,可能'std :: string'。 –

+0

@Andrey对于OP来说这不会很难,我没有写出完整的解决方案。您还需要'main' :) – Maroun

1

在你的第二个循环,你想:

std::string spc = " "; // add #include <string> at the top of the file 
for (int k = 0; k <= 5; k++) { 
    cout << spc; 
    for (int l = 5; l >= k; l--){ 
     cout << "*"; 
    } 
    spc += " "; 
    cout << endl; 
} 
1

你可以试试这个:http://ideone.com/hdxPQ7

#include <iostream> 

using namespace std; 

int main() 
{ 
    int i, j, k; 
    for (i=0; i<5; i++){ 
     for (j=0; j<i+1; j++){ 
      cout << "*"; 
     } 
     cout << endl; 
    } 
    for (i=0; i<5; i++){ 
     for (j=0; j<i+1; j++){ 
      cout << " "; 
     } 
     for (k=5; k>i+1; k--){ 
      cout << "*"; 
     } 
     cout << endl; 
    } 
    return 0; 
} 

这是它的输出:

* 
** 
*** 
**** 
***** 
**** 
    *** 
    ** 
    * 
0

希望这有助于(需要优化)。

void printChars(int astrks, int spcs, bool bAstrkFirst) 
{ 
    if(bAstrkFirst) 
    { 
     for(int j = 0; j<astrks;j++) 
     { 
      std::cout<<"*"; 
     } 
     for(int k = 0; k<spcs;k++) 
     { 
      std::cout<<" "; 
     } 
    } 
    else 
    { 

     for(int k = 0; k<spcs;k++) 
     { 
      std::cout<<" "; 
     } 
     for(int j = 0; j<astrks;j++) 
     { 
      std::cout<<"*"; 
     } 
    } 
    std::cout<<std::endl; 
} 

int main() 
{ 
    int astrk = 1, spc = 7; 
    for(int x = 0; x<5; x++) 
    { 
     printChars(astrk++, spc--, true); 
    } 
    for(int x = 0; x<5; x++) 
    { 
     printChars(--astrk, ++spc, false); 
    } 
    getchar(); 
    return 0; 
} 

输出:

* 
** 
*** 
**** 
***** 
    ***** 
    **** 
    *** 
     ** 
     *