c语言数组元素中偶数求和
时间: 2024-06-18 16:04:27 浏览: 19
首先,需要了解C语言中的数组和循环语句。可以使用循环语句遍历数组中的每一个元素,然后判断该元素是否为偶数,如果是,则加上该元素的值。最后得到的结果就是数组中偶数的总和。
以下是C语言实现数组元素中偶数求和的示例代码:
```c
#include <stdio.h>
int main()
{
int array[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int sum = 0;
for(int i = 0; i < 10; i++)
{
if(array[i] % 2 == 0) // 判断该元素是否为偶数
{
sum += array[i]; // 累加偶数元素的值
}
}
printf("数组中偶数的总和为:%d\n", sum);
return 0;
}
```
相关问题
c语言数组中奇偶求和
C语言中,可以通过循环遍历数组中的每一个元素,判断它是奇数还是偶数,然后分别累加到奇数和偶数两个变量中,最终得到奇数和偶数的和。具体实现如下:
```c
#include <stdio.h>
int main() {
int a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int odd_sum = 0; // 奇数和
int even_sum = 0; // 偶数和
for (int i = 0; i < 10; i++) {
if (a[i] % 2 == 0) { // 如果是偶数
even_sum += a[i]; // 加到偶数和中
} else { // 否则就是奇数
odd_sum += a[i]; // 加到奇数和中
}
}
printf("奇数和为:%d,偶数和为:%d\n", odd_sum, even_sum);
return 0;
}
```
c语言对数组中所有偶数求和
可以使用循环遍历数组,判断每个元素是否为偶数,如果是则累加到一个变量中,最后返回这个变量的值即可。以下是示例代码:
```c
#include <stdio.h>
int sum_even(int arr[], int len) {
int sum = 0;
for (int i = 0; i < len; i++) {
if (arr[i] % 2 == 0) {
sum += arr[i];
}
}
return sum;
}
int main() {
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int len = sizeof(arr) / sizeof(arr[0]);
int result = sum_even(arr, len);
printf("Sum of even numbers in the array: %d\n", result);
return 0;
}
```
输出结果为:
```
Sum of even numbers in the array: 30
```
相关推荐
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)