gpt4 book ai didi

c - C 数组中偶数索引处的元素之和

转载 作者:行者123 更新时间:2023-11-30 20:04:14 24 4
gpt4 key购买 nike

我有这个代码是为了对数组中偶数索引处的元素求和..

我想知道为什么我要写: for(i=1; i<size; i+2)不起作用?

#include <stdio.h>
#define SIZE 6

int func (int* arr, int size)
{
int i;
int j=2;
int sum=0;
for(i=0;i<size;i++)
if (arr[i] % 2 == 0) //why not for (i=1; i<size; i+2) ??????????
sum+=arr[i];
return sum;
}

void main()
{
int arr[SIZE]= {1,2,3,1,4,1};
printf ("%d", func (arr,SIZE));

}

谢谢

最佳答案

i + 2 不会更改 i 的值。您可以使用 i += 2i = i+2

#include <stdio.h>
#define SIZE 6

int func (int* arr, int size)
{
int i;
int j=2;
int sum=0;
for(i=0; i<size; i+=2) // now works since i is being modified.
sum+=arr[i];

return sum;
}

void main()
{
int arr[SIZE]= {1,2,3,1,4,1};
printf ("%d", func (arr,SIZE));
}

关于c - C 数组中偶数索引处的元素之和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42861642/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com