0
我正在寫一個關於清潔2維陣列中的灰塵的真空吸塵器的代碼。我希望這個清潔程序進入一行的結尾,然後回來完成下一行,依此類推。但是在這段代碼中,它會到第一行的末尾,並再次回到第一行的開頭!我該怎麼辦?非常感謝。For Loop in Vacuum cleaner
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand(time(0));
int i = 0;
int j;
int x = 0;
int y = 0;
int m = 0;
int t = 0;
int array[5][5];
int step = 0 , trash, total = 0, num = 0;
//Prepare the random array
for (x=0; x<5; x++)
{
for(y=0; y<5; y++)
{
array[x][y] = rand() % 2;
if (array[x][y] == 1)
{
total++;
}
}
}
//Print the total number of trashes based on the random number
cout<<endl<<"The total number of trashes are: "<<total<<endl<<endl;
//print the random array
for (x=0; x<5; x++)
{
for(y=0; y<5; y++)
{
cout<<array[x][y]<<"\t";
}
cout<<endl;
}
cout<<endl<<endl;
//------Manual Garbage Collector
cout<<"------ Manual Garbage Collector ------"<<endl<<endl;
while(num != total)
{
if(m % 2 != 0)
{
if(t==1)
i=1;
else if (t==3)
i=3;
for(i ; i<5 ; i++)
{
for(j=5 ; j>0 ; j--)
{
trash = array[i][j];
if(trash == 1)
{
cout<<"I found a trash in --> "<<"row: "<<i<<"\t column: "<<j<<endl;
num++;
step++;
}
else
{
step++;
}
}
m++;
t++;
break;
}
}
else if (m % 2 == 0)
{
if(t==2)
i=2;
else if (t==4)
i=4;
for(i ; i<5 ; i++)
{
for(j=0 ; j<5 ; j++)
{
trash=array[i][j];
if(trash == 1)
{
cout<<"I found a trash in --> "<<"row: "<<i<<"\t column: "<<j<<endl;
num++;
step++;
}
else
{
step++;
}
}
m++;
t++;
break;
}
}
}
cout<<endl<<"----------------"<<endl<<"The number of steps that I have tried: "<<step<<endl;
return 0;
}
的遍歷'我'永遠不會跑一次以上。在第一次(也是唯一一次)迭代結束時,你明確地將它從中斷出來;然後再輸入'i == 1' –
我使用了幾種解決方案來解決這個問題,但我找不到正確的答案。任何人都可以幫我,我該怎麼辦?謝謝。 – Sahand
這個問題有什麼不清楚的地方? – Sahand