2016-02-06 93 views
-1

我想这个嵌套转化为循环嵌套while循环:遇到问题从嵌套转化为循环嵌套while循环

程序:

#include<iostream> 
    using namespace std; 
    void main() 
    { 
    int i,j,n,stars=1; 
    cout<<"Enter the number of rows:"; 
    cin>>n; 
    for(i=1;i<=n;i++) 
    { 
     for(j=1;j<=stars;j++) 
      cout<<"*"; 
    cout<<"\n"; 
      stars=stars+1; 
    } 

    } 

,而试图嵌套while循环循环不停止有人请给我解决方案?

#include<iostream> 
using namespace std; 
void main() 
{ 
int n,i,j,k,stars=1; 
    cout<<"Enter the number of rows"; 
    cin>>n; 
    i=1; 
    while(i<=n) 
    { 
    j=1; 
    while(j<=stars) 
    { 
     cout<<"*"; 
     cout<<"\n"; 
     stars=stars+1; 
    } 
    j=j+1; 
} 
i=i+1; 

} 
+0

只需在内部while循环中移动'j = j + 1;'。 –

+1

不要这样做:'int n,i,j,k,stars = 1;',请。并使用空格键。 – LogicStuff

+0

C++ - 'void main' - 请(也使用'使用std' - 这是一个坏主意) –

回答

2

你必须incement您的控制varibales i ANS j您的环内。你之后直接将循环放在外面。除此之外,varibale stars在外部for循环中递增。在后面的代码片段中,您在内部while循环中完成了它。适应你的代码是这样的:如果

#include<iostream> 

int main() 
{ 
    int n; 
    std::cout<<"Enter the number of rows"; 
    std::cin>>n; 
    int stars=1; 
    int i=1; 
    while (i<=n)   // corresponds to for(i=1;i<=n;i++) { .... } 
    { 
     int j=1; 
     while (j<=stars) // corresponds to for(j=1;j<=stars;j++) cout<<"*"; 
     { 
      std::cout<<"*"; 
      j++;   // increment control variable inside of the loop 
     } 

     std::cout<<"\n"; 
     stars++; 
     i++;    // increment control variable inside of the loop  
    } 
    return 0; 
} 

注意你提高代码的格式,你会很容易找到这样的错误。