我需要打印此表
2
0
4 2
3 3
6 4 2
6 6 6
8 6 4 2
9 9 9 9
我为以下结果编写了这段代码
#include <iostream>
using namespace std;
int main(){
const int N = 9;
for(int i = 0; i <= N; i += 3){
for (int j = 0; j <= i; j +=3) {
cout << i << " ";
}
cout << endl;
}
cout << "\n";
for(int i = 2; i <= N; i += 2){
for (int j = i; j > 0; j -= 2) {
cout << j << " ";
}
cout << endl;
}
return 0;
}
我的结果:
0
3 3
6 6 6
9 9 9 9
2
4 2
6 4 2
8 6 4 2
必填结果:
2
0
4 2
3 3
6 4 2
6 6 6
8 6 4 2
9 9 9 9
答案 0 :(得分:1)
#include <iostream>
using namespace std;
int main(){
const auto n = 4;
auto count = 0;
for (auto i = 2; i <= n * 2; i += 2)
{
for (auto j = i; j > 0; j -= 2)
std::cout << j << " ";
std::cout << std::endl;
for (auto j = 0; j < (i == 2 ? i : i + 2); j += 3)
std::cout << count * 3 << " ";
++count;
std::cout << std::endl;
}
return 0;
}
编辑:已更正...
有点接近答案
2
0 ==>是
4 2
0 3 ==>应该是3 3
6 4 2
0 3 6 ==>应该是6 6 6
8 6 4 2
0 3 6 ==>应该是9 9 9
答案 1 :(得分:1)
这是提供重复次数(例如在@Ruks答案中)的另一种方法:
void printSequence(unsigned int repeats)
{
int n = 2;
for(int i = 1; i < repeats; i++)
{
n+=2*i;
}
//n - number of all numbers in sequence for given number of repeats
int step = 0;
int numsPerRow = 1;
for(int i = 0; i < n; i+=step)
{
for(int j = numsPerRow; j > 0; j--)
{
std::cout << 2*j << " ";
}
std::cout << std::endl;
for(int j = 0; j < numsPerRow; j++)
{
std::cout << step+numsPerRow-1 << " ";
}
std::cout << std::endl;
step+=2;
numsPerRow++;
}
}
答案 2 :(得分:0)
使用此:
void print_sequence(unsigned long long const repeat = 4, unsigned long long const i = 0)
{
for (auto j = (i + 1ull) * 2ull; j > 2ull; j -= 2ull)
std::cout << j << " ";
std::cout << (repeat > 0ull && repeat < -1ull ? "2\n" : "");
for (auto j = 0ull; j < i; j++)
std::cout << i * 3ull << " ";
std::cout << (repeat > 0ull && repeat < -1ull ? std::to_string(i * 3ull) + "\n" : "");
if (repeat < -1ull && i + 1ull < repeat)
print_sequence(repeat, i + 1ull);
}
编辑:我能想到的最短,最强的方法...
并这样称呼它:
print_sequence();
如果您不想4次:
print_sequence(10)
它将重复您想要的多次...
亲切的问候,
Ruks。