我有一个想法,要制作一个程序,它可以接受用户的输入,并制作一个.我不太清楚如何正确称呼它,所以我的WIP是自上而下的金字塔。这样我们就不会搞混了,应该是这样的。
如果c为5:
11111
10001
10101
10001
11111如果c为7:
0000000
0111110
0100010
0101010
0100010
0111110
0000000唯一的条件是中间一定有1,而cin是奇怪的。
现在,我在业余时间一直在考虑这个问题,这在我的头脑中似乎很容易,但是当我试图将我的想法放在我的代码中时,它永远都无法实现。有人能帮我吗?我很绝望。-。
这是到目前为止我的WIP代码(请原谅我的捷克国家和文本)
#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;
}发布于 2018-01-31 20:24:57
为了解决这类问题,如果你发现你需要一个new,那么事情就不对劲了。只要继续跟踪打印的当前状态,一切都可以一次完成.
#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;
}
}
}https://stackoverflow.com/questions/48548145
复制相似问题