我有以下代码:
int array[5] = {1, 0, 1, 0, 0};
int i;
for(i = 0; i < 5; i++)
{
if(array[i] == 1)
{
printf("found onen");
}
}
我们怎么知道array
中的第二个1
是我们找到的最后一个1
?我的意思不是保持最后一个1
的值,我的意思是我们怎么知道第二个1
是最后一次出现,不再出现?
您可以简单地按相反的顺序循环:
for(i = 4; i >= 0; i--)
{
if(array[i] == 1)
{
printf("last 1 found!n");
//break or do whatever you want
}
}
我们可以进一步改进代码如下:
int main(){
int array[] = {1, 0, 1, 0, 0}, i;
for(i=sizeof(array)/sizeof(int)-1; array[i]!=1 && --i;);
printf("last 1 found at index = %dn", i);
return 1;
}
编码板。
第二种形式的代码还有一些额外的好处:
- 包括初始化
- 数组的大小独立性
- 快速有两种方式:&;,
--i
将在需要时执行 - 较小的代码(删除了
if()
、break
)
您可以跟踪找到"1"的最后一个索引。例如:
int array[5] = {1, 0, 1, 0, 0};
int i;
int lastIndexOf=-1;
for(i = 0; i < 5; i++)
{
if(array[i] == 1)
{
lastIndexOf=i;
printf("found onen");
}
}
if(lastIndexOf!=-1)
printf("last index of 1 : %dn",lastIndexOf);
设置一个等于0&每次找到1时递增。当数组被完全解析后,您将知道哪个1是最后一个1。
int counter = 0;
int lastone = -1;
for(i = 0; i < 5; i++)
{
if(array[i]==1)
{
counter++;
lastone = i;
printf("found onen");
}
}
if(lastone!=-1)
printf(" %d one is the last one %d", counter, lastone);