0

我认为这比最初计划的要容易。我正在尝试使此图像脱离嵌套的 for 循环:

在此处输入图像描述

任何建议或解决方案都会有所帮助。

#include <iostream>

using namespace std;

int main()
{
    for(int i=0; i<1;i++)
    {
        cout<<i+1<<endl;

        for(int j=0;j<2;j++)
        {
            cout<<j+1;
        }
     }

    cout<<"\n";
    for(int k=0; k<3; k++)
    {
        cout<<k+1;
    }
    cout<<"\n";
    for(int l=0; l<4; l++)
    {
        cout<<l+1;
    }
    cout<<"\n";
    for(int m=4; m>0; m--)
    {
        cout<<m;
    }
    cout<<"\n";
    for(int n=3; n>0; n--)
    {
        cout<<n;
    }
    cout<<"\n";
    for(int o=2; o>0; o--)
    {
        cout<<o;
    }
    cout<<"\n";
    for(int p=0; p<1; p++)
    {
        cout<<p+1;
    }
    cin.get();

    return 0;
}
4

4 回答 4

4

这是为您提供的 C 解决方案 =)

#include <stdio.h>
#include <string.h>

int main(void) {
    char forward[5] = "1";
    char reverse[5] = "4321";

    int i;
    for( i = 1; i <= 4; i++ ) {
        printf( "%s\n", forward );
        forward[i] = forward[i-1]+1;
    }
    for( i = 0; i < 4; i++ ) printf( "% 4s\n", reverse+i );
}
于 2013-02-15T04:59:52.867 回答
3

如果您想要一个非常紧凑且不太容易遵循的解决方案,我决定试一试。

int length = 4;

for(int i = 0; i < 2; i++) 
{
    for(int j = 0; j < length; j++) 
    {
        for(int k = 0; k < (i == 1 ? length - j : j + 1); k++) 
        {
            if(i == 1 && k == 0) 
                for(int x = 0; x < j; x++)
                    cout << " ";

            cout << (i == 1 ? (length - k) - j : k + 1);
        }

        cout << endl;
    }
}

从到length的迭代次数在哪里。1length

输出

于 2013-02-15T05:06:53.437 回答
2

好的,因为 paddy 发布了他的 C 解决方案(有人说“紧凑”=P)......

#include <stdio.h>
int main()
{
    char line[] = "1234321";
    int i=0;
    for (; i<4; printf("%.*s\n",++i,line));
    for (i=0;i<4; printf("%4s\n",line+3+i++));
    return 0;
}

输出

1
12
123
1234
4321
 321
  21
   1
于 2013-02-15T05:42:18.873 回答
0
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
 /*first half: From level1 = 1 to less than 5, level2 = 1 to less than or equal to level1, print level2 */
 for(int level1 = 1; level1 < 5; level1++) { 
     for(int level2 = 1; level2 <= level1; level2++){
        cout << level2;
     }
     cout << '\n'; /*prints the newline AFTER each iteration of the `level2` loop*/
 }

 /*second half: reverse the logic of part1, but also add spaces in the beginning */
 for(int level1 = 4; level1 > 0; level1--){
     for(int interim = 4; interim > level1; interim--) cout << ' ';
     for(int level2 = level1; level2 > 0; level2--){
         cout << level2;
     }
     cout << '\n';
 }
 return 0;  
}

如果您不理解此代码,请告诉我 :-)

于 2013-02-15T04:41:39.127 回答