首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++ TopDown金字塔

C++ TopDown金字塔
EN

Stack Overflow用户
提问于 2018-01-31 17:31:31
回答 1查看 63关注 0票数 0

我有一个想法,要制作一个程序,它可以接受用户的输入,并制作一个.我不太清楚如何正确称呼它,所以我的WIP是自上而下的金字塔。这样我们就不会搞混了,应该是这样的。

如果c为5:

代码语言:javascript
复制
11111
10001
10101
10001
11111

如果c为7:

代码语言:javascript
复制
0000000
0111110
0100010
0101010
0100010
0111110
0000000

下面是一个帮助可视化问题的图像

唯一的条件是中间一定有1,而cin是奇怪的。

现在,我在业余时间一直在考虑这个问题,这在我的头脑中似乎很容易,但是当我试图将我的想法放在我的代码中时,它永远都无法实现。有人能帮我吗?我很绝望。-。

这是到目前为止我的WIP代码(请原谅我的捷克国家和文本)

代码语言:javascript
复制
#include <iostream>

using namespace std;

void FillArray(int **PyramidArray,int a,int b,int c);
void ExtractArray(int **PyramidArray,int a,int b,int c);
int main()
{
cout << "input array size.(only odd numbers)" << endl;
int c;
cin >> c;
if (c%2 == 0)
{
cout << "Only odd numbers!" << endl;
return 1;
}
int **PyramidArray;
    PyramidArray = new int*[c];
    for (int i =0;i<c;i++)
    {
        PyramidArray[i] = new int[i];
    }
    FillArray(PyramidArray,c,c,c);
    ExtractArray(PyramidArray,c,c,c);



return 0;
}

void FillArray(int **PyramidArray, int a, int b, int c)
{

    for(int i=0;i<a;i++)
    {

        for (int j=0;j<b;j++)
        {
            PyramidArray [i][j] = 1;
        }
    }

 }
void ExtractArray(int **PyramidArray, int a,int b,int c)
 {
for(int i=0;i<a;i++)
    {
    for (int j=0;j<b;j++)
        {
        cout << PyramidArray [i][j] << " ";
        }
        cout << endl;
    }
    cout << endl;
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-01-31 20:24:57

为了解决这类问题,如果你发现你需要一个new,那么事情就不对劲了。只要继续跟踪打印的当前状态,一切都可以一次完成.

代码语言:javascript
复制
#include <iostream>

int main() {
    int n = 0, half_n = 0;

    std::cin >> n;
    if ( n % 2 == 0 ) return -1;
    half_n = n / 2;

    // the first symbol to print, 1 or 0
    int start_symbol = 1 - half_n % 2;

    // how many steps from beginning require alternating symbol ?
    int alternate_range = 0;

    // 0 for upperhalf, 1 for lowerhalf
    int direct = 0; 

    for ( int i = 0; i < n; ++i ) {
        int current_symbol = start_symbol;
        for ( int j = 0; j < alternate_range; ++j ) {
            std::cout << current_symbol;
            current_symbol = 1 - current_symbol;
        }

        for ( int j = alternate_range; j < n - alternate_range; ++j ) {
            std::cout << current_symbol;
        }

        for ( int j = n - alternate_range; j < n; ++j ) {
            current_symbol = 1 - current_symbol;
            std::cout << current_symbol;
        }
        std::cout << "\n";

        if ( alternate_range == half_n ) {
            direct = 1;
        }

        if ( direct == 0 ) {
            ++alternate_range;
        } else {
            --alternate_range;
        }
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48548145

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档