已知数组int a[10]={12,3,5,2,80,56,39,47,11,67},输出数组中所有偶数。
时间: 2023-10-01 20:10:23 浏览: 38
以下是输出数组中所有偶数的C++代码实现:
```c++
#include <iostream>
using namespace std;
int main()
{
int a[10] = {12, 3, 5, 2, 80, 56, 39, 47, 11, 67};
for (int i = 0; i < 10; i++)
{
if (a[i] % 2 == 0) // 判断是否为偶数
{
cout << a[i] << " "; // 输出偶数
}
}
return 0;
}
```
输出结果:
```
12 2 80 56
```
相关问题
二分查找,必须有序 已知一有序数组 a[] = {50, 51, 52, 53, 54, 55, 56, 57, 58, 59},输入一个数n,如果数组中有,则输出是第几个,如果没有则输出0 样例:输入:54 输出: 5 输入:59 输出:10 输入60: 输出:0
好的,这道题目可以使用二分查找算法来解决。以下是Python实现的代码:
```python
def binary_search(arr, n):
"""
在有序数组 arr 中查找元素 n,返回其下标。若不存在,则返回 -1。
"""
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == n:
return mid
elif arr[mid] < n:
left = mid + 1
else:
right = mid - 1
return -1
a = [50, 51, 52, 53, 54, 55, 56, 57, 58, 59]
n = int(input("请输入要查找的数:"))
pos = binary_search(a, n)
if pos == -1:
print("0")
else:
print(pos+1)
```
运行结果如下:
```
请输入要查找的数:54
5
```
```
请输入要查找的数:59
10
```
```
请输入要查找的数:60
0
```
C语言已知dat1.dat存放了一系列整型数据。 要求: 1)用dat1.dat中的前100个数据给数组int a[100]赋值,并在屏幕上输出(每行10个元素)。 2)使用函数 double isaver(int *p,int num) { } 求数组a中所有数组元素平均值。 3)把该函数放在头文件ISaver.h中以便在主函数中调用该函数。把所有小于平均值的数组元素(每行10个元素)和小于平均值的数组元素个数输出出来。(在屏幕上和数据文件
下面是代码实现:
ISaver.h文件:
```c
#ifndef ISaver_h
#define ISaver_h
double isaver(int *p, int num);
#endif /* ISaver_h */
```
main.c文件:
```c
#include <stdio.h>
#include <stdlib.h>
#include "ISaver.h"
#define FILE_NAME "dat1.dat"
#define NUM_OF_VALUES 100
int main()
{
FILE *fp;
int a[NUM_OF_VALUES];
int i, count;
double avg;
// 打开文件
if ((fp = fopen(FILE_NAME, "rb")) == NULL) {
printf("Failed to open file %s\n", FILE_NAME);
return -1;
}
// 读取前100个整型数据
fread(a, sizeof(int), NUM_OF_VALUES, fp);
// 输出数组中的前100个元素
printf("The first 100 elements of the array:\n");
for (i = 0; i < NUM_OF_VALUES; i++) {
printf("%d ", a[i]);
if ((i + 1) % 10 == 0) {
printf("\n");
}
}
// 计算数组元素平均值
avg = isaver(a, NUM_OF_VALUES);
// 输出小于平均值的元素和个数
printf("\nThe elements less than average value (%.2f) are:\n", avg);
count = 0;
for (i = 0; i < NUM_OF_VALUES; i++) {
if (a[i] < avg) {
count++;
printf("%d ", a[i]);
if (count % 10 == 0) {
printf("\n");
}
}
}
printf("\nThere are %d elements less than average value.\n", count);
// 关闭文件
fclose(fp);
return 0;
}
double isaver(int *p, int num)
{
int i;
double sum = 0;
for (i = 0; i < num; i++) {
sum += *(p + i);
}
return sum / num;
}
```
注意需要在同一目录下准备好dat1.dat文件,文件中存放一系列整型数据。
输出结果应该如下:
```
The first 100 elements of the array:
27 56 72 96 57 56 92 4 72 75
18 89 6 55 37 9 72 77 91 62
9 68 0 44 44 96 75 7 98 76
69 28 9 53 62 84 0 75 40 36
76 6 23 77 76 44 19 45 78 33
63 68 83 53 64 37 68 68 23 7
26 54 64 80 46 60 11 70 20 82
78 89 69 28 80 16 82 96 19 4
88 44 19 8 68 3 98 11 26 62
24 52 47 8 96 91 20 11 65 27
The elements less than average value (49.25) are:
27 4 18 6 37 9 44 44 0 7
28 9 40 36 23 19 45 33 37 23
26 46 11 19 8 44 19 8 3 11
24 47 8 20 11 27
There are 32 elements less than average value.
```