我制作了一個代碼,可以產生這種輸出:
1 2 3 4 5 6
7 8 9 10 11 12
13 14 15 16 17 18
19 20 21 22 23 24
25 26 27 28 29 30
31 32 33 34 35 36
37 38 39 40 41 42
43 44 45 46 47 48
#include <iostream>
using namespace std;
int main() {
// dimensions:
int x=6,y=8;
int sum=0;
int numery[8][6]={};
for (i = 0; i < y; i ) {
for (j = 0; j < x; j ) {
numery[i][j]= sum;
if (numery[i][j]<=9) cout << " ";
cout << numery[i][j] << " ";
}
cout << endl;
}
return 0;
}
但我不知道如何編輯它以獲得這種輸出:
6 5 4 3 2 1
7 8 9 10 11 12
18 17 16 15 14 13
19 20 21 22 23 24
30 29 28 27 26 25
31 32 33 34 35 36
37 38 39 40 41 42
43 44 45 46 47 48
我可以考慮為每個 i%2==1 做 if 陳述句,它應該倒退,但我不知道如何讓程式做這樣的事情。否則它應該會正常進行。因此,如果它找到偶數行,它應該像 7 8 9 10 11 12,而如果它是 i%2==1,它應該像 6 5 4 3 2 1 等等。一些建議?
uj5u.com熱心網友回復:
一種解決方案如下(我假設您實際上不需要存盤數字)。請注意,setw()可用于列印固定寬度的數字:
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
// dimensions:
int x=6,y=8;
for (int i = 0; i < y; i )
{
for (int j = 0; j < x; j )
{
cout << setw(3) << ((i%2) ? i*x j 1 : i*x x-j) << " ";
}
cout << endl;
}
return 0;
}
uj5u.com熱心網友回復:
首先擺脫陣列。這是不必要的。
#include <iostream>
using namespace std;
int number(int i,int j,int width) { return j i*width 1 ;}
int main() {
// dimensions:
int x=6,y=8;
for (int i = 0; i < y; i ) {
for (int j = 0; j < x; j ) {
auto n = number(i,j,x);
if (n <= 9) cout << " ";
cout << n << " ";
}
cout << endl;
}
return 0;
}
這與您的代碼具有相同的輸出。
接下來考慮j當你倒車時會發生什么。你應該想到,通過,答案是:你替換j用width-j-1。
int number_reverse(int i,int j, int width) { return number(i,width-j-1,width); }
最終你只需要在外回圈的每次迭代中呼叫正確的函式:
#include <iostream>
using namespace std;
int number(int i,int j,int width) { return j i*width 1 ;}
int number_reverse(int i,int j, int width) { return number(i,width-j-1,width); }
int main() {
// dimensions:
int x=6,y=8;
for (int i = 0; i < y; i ) {
for (int j = 0; j < x; j ) {
auto n = (i%2) ? number_reverse(i,j,x) : number(i,j,x);
if (n <= 9) cout << " ";
cout << n << " ";
}
cout << endl;
}
return 0;
}
uj5u.com熱心網友回復:
這是一個解決方案,以防您確實需要將數字存盤在陣列中。
#include <iostream>
using namespace std;
int main() {
// dimensions:
int x=6,y=8;
int sum=0;
int numery[y][x];
for (int i = 0; i < y; i )
for (int j = 0; j < x; j )
numery[i][j]= sum;
for(int i = 0; i < y; i )
{
if(i%2 == 0)
{
for(int j = x-1; j >= 0; --j)
{
if(numery[i][j] < 10)
{
cout << " ";
}
cout << numery[i][j] << " ";
}
cout << endl;
}
else
{
for(int j = 0; j < x; j )
{
if(numery[i][j] < 10)
{
cout << " ";
}
cout << numery[i][j] << " ";
}
cout << endl;
}
}
return 0;
}
您首先將數字分配給您的陣列。然后根據是否在偶數行或奇數行上從后到前或從前到后列印數字。
uj5u.com熱心網友回復:
如果您愿意以非線性順序填充陣列,則可以從右到左每隔一行填充:array[i][x-1-j]= sum;。
另一種方法是使用一個外回圈和兩個內回圈,注意所有行都是 form a*i b*j c,其中 b 是 1 或 -1。這簡化array[i][j] = 6*i 6 - j了偶數行和array[i][j]=6*i 1 j奇數行。
另一種選擇是有一個單一的內回圈,它將增加或減少一定數量 d = i % 2 == 0 ? -1 : 1;
for (int j = 0; j<x; j ) { arr[i][j]=sum; sum = d;}
sum =6-d;
在每一行之后,我們需要補償變數,sum以便它從下一個索引的正確值開始i 1。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/331749.html
標籤:C
