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