.一维数组a中的元素为:1,4,2,7,3,12,5,34,5,9。求一维数组a中的最大 元素及其下标。程序的输出应为:The max is: 34, position is:7。 要求:求 最大元素位置用函数实现,在main 函数中调用该函数。
时间: 2023-07-30 20:09:34 浏览: 35
以下是用 C++ 实现的代码:
```cpp
#include <iostream>
using namespace std;
int findMax(int arr[], int size) {
int maxNum = arr[0];
int maxPos = 0;
for (int i = 1; i < size; i++) {
if (arr[i] > maxNum) {
maxNum = arr[i];
maxPos = i;
}
}
return maxPos;
}
int main() {
int a[] = {1, 4, 2, 7, 3, 12, 5, 34, 5, 9};
int size = sizeof(a) / sizeof(int);
int maxPos = findMax(a, size);
cout << "The max is: " << a[maxPos] << ", position is: " << maxPos << endl;
return 0;
}
```
输出结果为:
```
The max is: 34, position is: 7
```
相关问题
2.一维数组:中的元素为:1,4.2.7,3,12,5,34,5,9。求一维数组a中的最大 元素及其下标。程序的输出应为:Themaxis:34,positioris:7。要求:求 最大元素位置用函数实现,在main函
数中调用该函数。
可以参考以下代码实现:
```c
#include <stdio.h>
int findMax(int arr[], int size) {
int max = arr[0];
int index = 0;
for (int i = 1; i < size; i++) {
if (arr[i] > max) {
max = arr[i];
index = i;
}
}
printf("The max is: %d, position is: %d\n", max, index);
return max;
}
int main() {
int a[] = {1, 4, 2, 7, 3, 12, 5, 34, 5, 9};
int size = sizeof(a) / sizeof(a[0]);
int max = findMax(a, size);
return 0;
}
```
输出结果为:
```
The max is: 34, position is: 7
```
求一维数组a中值为偶数的元素之和。 例如: 输入 10 4 2 7 3 12 5 34 5 9 输出 The result is:62
好的,这是一个求一维数组中偶数和的问题,我来给您写一个程序:
```c
#include <stdio.h>
int main() {
int a[10], sum = 0, i;
for (i = 0; i < 10; i++) {
scanf("%d", &a[i]);
if (a[i] % 2 == 0) {
sum += a[i];
}
}
printf("The result is:%d", sum);
return 0;
}
```
上述程序首先定义了一个长度为10的一维数组a和一个变量sum,用于存储偶数元素的和。然后使用for循环遍历数组a,从控制台逐个读入数组元素。在每次读入元素时,使用if语句判断该元素是否为偶数,如果是,则将其加入sum中。最后输出sum即可。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://img-home.csdnimg.cn/images/20210720083646.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)