菱形内部,输出编号为1至9 C ++

时间:2017-11-11 05:16:15

标签: c++ loops for-loop

所以我得到了这段代码。

int n;
int m=1;
int a=9;

cout<<"Enter N Number = ";
cin>>n;

n=n*2-1;

for(int y=1;y<=n;y++)
{
    for(int x=1;x<=n;x++)
    {
        if(x==y+n/2 || x==y-n/2 || x==n-y+1-n/2 || x==n-y+1+n/2)
        {
            if(m<=9)
            {
                cout<<m++;
            }
            else if(m>9&&a>0)
            {
                a--;
                cout<<a;
            }  
        }
        else
        {
            cout<<" ";
        }
    }
    cout<<endl;
}

这就是我得到的:

Diamond Shape(Fail)

而我所期望的是形状底部没有数字“0”,因此在打印数字1之后它会反弹回2,3号等等

请原谅我的英语不好

1 个答案:

答案 0 :(得分:-1)

你想要它是这样的吗? Check this out!

我可以用Pascal,C ++和Java编写代码。 PS:我也不是母语为英语的人。

第一个答案:这不是最好的答案,明天下午我会改进。

#include <iostream>
using namespace std;

int get() {
    static int counter = 0;
    static bool reverse = false;
    !reverse ? counter++ : counter--;
    if (counter==10 or counter==0) reverse = !reverse;
    counter==10 ? counter = 8 : 0;
    counter==0 ? counter = 2 : 0;
    return counter;
}
int main() {
    int number;

    cout << "Enter N Number = ";
    cin >> number;
    //forward:
    for (int i = 0; i < number; i++) {
        for (int j = number-i-1; j > 0; j--)
            cout << " ";
        cout << get();
        if (i!=0) {
            for (int j = 0; j < i * 2 -1; j++) cout << " ";
            cout << get();
        }
        cout << endl;
    }
    //backward:
    for (int i = number-1; i > 0 ; i--) {
        for (int j = number-i; j > 0; j--)
            cout << " ";
        cout << get();
        if (i!=1) {
            for (int j = i * 2 -3; j > 0; j--) cout << " ";
            cout << get();
        }
        cout << endl;
    }
    return 0;
}

第二个答案:改进循环

#include <iostream>
using namespace std;

int nextNumber() {
    static int counter = 0;
    static bool reverse = true;
    !reverse ? counter++ : counter--;
    if (counter==-1) counter=1; 
    if (counter==9 or counter==1) reverse = !reverse;
    return counter;
}
int main() {
    int number;
    cout << "Enter N Number = ";
    cin >> number;
    int space = number;
    int middle = -3;
    for (int row = 0; row < number*2-1; row++) {
        if(row<number) {
            space--;
            middle += 2;
        }
        else {
            space++;
            middle -= 2;
        }
        for (int i = 0; i < space; i++)
            cout << " ";
        cout << nextNumber();
        if(row!=0 and row!=number*2-2) {
            for (int i = 0; i < middle; i++)
                cout << " ";
            cout << nextNumber();
        }
        cout << endl;
    }
    return 0;
}