我似乎对我的代码遇到的问题是for循环似乎没有在正确的时间中断。我们的想法是,当数组中的所有值都大于零时,for循环就会中断。问题是不会发生中断。这是我的代码。
#include<stdio.h>
int randomInt(int max)
{
return (random(2)%max);
}
main()
{
int i,k=0,j;
int position=1,r=1; /*Position indicates the position of the particle
and r represents where the particle will move
next*/
int seed,L=10,M=20;/*L is the number of sites and M is the number of hops*/
float n,sum=0;
float average;
int frequency[M];
for(i=0;i<(M);i++)
{
frequency[i]=0;
}
//setup the random seed generator
printf("\nEnter your value of seed\n");
scanf("%d",&seed);
srandom(seed);
for(i=0;i<M;i++) //This loops around the total number of loops.
{
printf("\nThe particle is at position %d\n",position);
n=randomInt(2);/*This chooses either the numbers 0 or 1 randomly */
frequency[position]=frequency[position]+1;
printf("This position has been visited %d times\n",frequency[position]);
sum=sum+frequency[position];
/*Below represents the conditions which will determine the movement
of the particle*/
if(n==0)
{
r=1;
}
if(n==1)
{
r=-1;
}
position = position + r;
if(position==0)
{
position=L;
}
if(position==L+1)
{
position=1;
}
//This 'for' loop below is used to check if all the sites have been visited.
for(j=0;j<(L-1);j++)
{
if(frequency[j]==0)
{
k++;
}
}
if(k==0)
{
break;
}
if(k!=0)
{
k=0;
}
}
printf("\nThe particle hopped %d times when it visited every site\n",i);
printf("\nThe total frequency of hops is %.lf\n",sum);
average=sum/i;
printf("\nAverage number of hops made when all the sites have been visited %.2lf\n",average);
}
答案 0 :(得分:3)
那是因为你只是退出内部嵌套的for
循环。两者中break
的最佳方法是设置一些bool
标志,在从内循环中断开时将其设置为true
,然后检查外部条件:
bool flag = false;
然后在内心:
flag = true;
break;
然后在外面:
if(flag) break;
编辑:
如果我误解了,你只想打破内心,它发生的原因也可能是你在每次更大的迭代后都没有将你的k
重置为零,所以如果下一个数组是零的话只有k
仍然具有旧值,并且最终永远不会保留0
。