我不想反轉或移動陣列。我想要的是從右到左寫陣列。
我做了類似的事情
int arr[5] = {0};
for (int i = 0; i < 5; i )
{
cout << "enter a number : ";
cin >> arr[i];
for (int j = 0; j < 5; j )
{
if (arr[j] != 0)
{
cout << arr[j] << " ";
}
else
cout << "X ";
}
cout << endl;
}
在輸出螢屏上我看到了這個
enter a number : 5
5 X X X X
enter a number : 4
5 4 X X X
enter a number : 3
5 4 3 X X
enter a number : 2
5 4 3 2 X
enter a number : 1
5 4 3 2 1
Press any key to continue . . .
但我想看看這個
enter a number : 5
X X X X 5
enter a number : 4
X X X 5 4
enter a number : 3
X X 5 4 3
enter a number : 2
X 5 4 3 2
enter a number : 1
5 4 3 2 1
Press any key to continue . . .
我怎樣才能做到這一點?
如果你能幫忙,我會很高興。
uj5u.com熱心網友回復:
只需更改內部 for 回圈,例如以下方式
int j = 5;
for ( ; j != 0 && arr[j-1] == 0; --j )
{
std::cout << 'X' << ' ';
}
for ( int k = 0; k != j; k )
{
std::cout << arr[k] << ' ';
}
uj5u.com熱心網友回復:
我認為您每次都嘗試寫入最后一個索引,然后在陣列中向后移動每個數字?
要寫入最后一個索引,請使用 cin >> arr[4]。然后在列印出陣列后將每個值復制到前一個索引中。確保您的副本僅在 J 索引小于 4 時
int arr[5] = {0};
for (int i = 0; i < 5; i )
{
cout << "enter a number : ";
//write into the last position
cin >> arr[4];
for (int j = 0; j < 5; j )
{
if (arr[j] != 0)
{
cout << arr[j] << " ";
}
else
cout << "X ";
//don't go out of bounds. This should move each number to the previous index
if(j<4){
arr[j]=arr[j 1];
}
}
cout << endl;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/465253.html
下一篇:如何回圈另一個回圈以填充矩陣
