我们怎么会知道这是在数组中的最后一个元素? [英] how could we know this is the last element in the array?
本文介绍了我们怎么会知道这是在数组中的最后一个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下的code:
int array[5] = {1, 0, 1, 0, 0};
int i;
for(i = 0; i < 5; i++)
{
if(array[i] == 1)
{
printf("found one\n");
}
}
我们怎么会知道第二个 1
在阵列
是最后一个 1
我们发现?
我的意思不是保持过去 1
,我的意思是,我们应该怎么知道第二个 1
是值了最后一次出现,没有更多的显示出来?
how could we know the second 1
in the array
is the last 1
we found?
I do not mean keep the value of last 1
, what I mean is how should we know the second 1
is the last occurence, no more shows up?
推荐答案
您可以简单地循环以相反的顺序:
You can simply loop in a reverse order:
for(i = 4; i >= 0; i--)
{
if(array[i] == 1)
{
printf("last 1 found!\n");
//break or do whatever you want
}
}
我们可以进一步提高code如下:
We can further improve the code as follows:
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 = %d\n", i);
return 1;
}
codePAD 。
code的第二种形式有一些额外的好处:
The second form of code has some additional benefits:
- 包括初始化。
- 数组的大小独立。
- 快速在两个方面:的&安培短路行为;&安培;,
- 我
将被执行。 - 小code(删除
如果()
,破
)。
- Include initialization.
- Size independence of array.
- Fast in two ways: Short-circuit behavior of &&,
--i
will be performed when needed. - Smaller code (removed
if()
,break
).
这篇关于我们怎么会知道这是在数组中的最后一个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文