c语言用函数求数组中偶数之和
时间: 2024-06-13 08:07:45 浏览: 22
以下是C语言用函数求解数组中偶数之和的代码:
```c
#include <stdio.h>
int sum(int v[], int n);
int main() {
int v[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int n = sizeof(v) / sizeof(v[0]);
int result = sum(v, n);
printf("The sum of even numbers is %d\n", result);
return 0;
}
int sum(int v[], int n) {
int i, sum = 0;
for (i = 0; i < n; i++) {
if (v[i] % 2 == 0) {
sum += v[i];
}
}
return sum;
}
```
相关问题
c语言找出数组中偶数的函数
下面是一个简单的 C 语言函数,用于找出数组中的偶数:
```c
void findEven(int arr[], int size) {
printf("Even numbers in the array are: ");
for (int i = 0; i < size; i++) {
if (arr[i] % 2 == 0) {
printf("%d ", arr[i]);
}
}
}
```
该函数接受两个参数:一个整数数组和数组的大小。它遍历整个数组并打印出所有的偶数。可以在主函数中调用此函数:
```c
int main() {
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int size = sizeof(arr) / sizeof(arr[0]);
findEven(arr, size);
return 0;
}
```
输出结果为:
```
Even numbers in the array are: 2 4 6 8
```
使用C语言输出字符数组中下标为偶数的字符
好的,可以使用以下代码实现:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World!";
int len = strlen(str);
int i;
for (i = 0; i < len; i += 2) {
printf("%c ", str[i]);
}
return 0;
}
```
这里定义了一个字符数组 `str`,然后使用 `strlen()` 函数获取其长度。接着使用 `for` 循环遍历字符数组,每次增加2个下标,并使用 `printf()` 函数输出对应的字符。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![c](https://img-home.csdnimg.cn/images/20210720083646.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)
![](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)