c/c++语言开发共享我们怎么知道这是数组中的最后一个元素?

我有以下代码:

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是最后一个出现,不再出现?

    您可以按相反的顺序循环:

     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; } 

    键盘 。

    第二种代码forms还有一些额外的好处:

    您可以跟踪找到“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。

     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); 

      以上就是c/c++开发分享我们怎么知道这是数组中的最后一个元素?相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/544658.html

      (0)
      上一篇 2021年1月9日
      下一篇 2021年1月9日

      精彩推荐