C++求:假设有数组a[10]=(15,11,25,78,90,12,22,85,36,18]; 设计程序查找并输出其最大值和最小值。
时间: 2023-08-21 17:03:29 浏览: 34
好的,以下是求解过程:
```cpp
#include <iostream>
using namespace std;
int main() {
int a[10] = {15, 11, 25, 78, 90, 12, 22, 85, 36, 18};
int max_val = a[0]; // 最大值
int min_val = a[0]; // 最小值
for (int i = 1; i < 10; i++) {
if (a[i] > max_val) {
max_val = a[i];
}
if (a[i] < min_val) {
min_val = a[i];
}
}
cout << "最大值:" << max_val << endl;
cout << "最小值:" << min_val << endl;
return 0;
}
```
输出结果为:
```
最大值:90
最小值:11
```
程序中,我们使用了 `for` 循环遍历数组中的每一个元素,然后再与当前的最大值和最小值进行比较,如果大于最大值则更新最大值,如果小于最小值则更新最小值。最后输出最大值和最小值即可。
相关问题
假设有数组a[10]={15,11,25,78,90,12,22,85,36,18}; 设计程序查找并输出其最大值和最小值。
好的,我可以帮你写一个 C++ 的程序来实现这个功能。程序如下:
```cpp
#include <iostream>
using namespace std;
int main() {
int a[10] = {15, 11, 25, 78, 90, 12, 22, 85, 36, 18};
int max_val = a[0], min_val = a[0];
for(int i = 1; i < 10; i++) {
if(a[i] > max_val) {
max_val = a[i];
}
if(a[i] < min_val) {
min_val = a[i];
}
}
cout << "最大值为:" << max_val << endl;
cout << "最小值为:" << min_val << endl;
return 0;
}
```
程序首先定义了一个包含10个元素的整型数组a,并初始化了其值。接着定义了两个变量max_val和min_val,分别用来存储最大值和最小值。然后使用for循环遍历数组a,依次比较每个元素与当前最大值和最小值的大小,并更新max_val和min_val的值。最后输出最大值和最小值即可。
假设有数组a[10]={15,11,25,78,90,12,22,85,36,18}; 设计程序查找并输出其次大值和次小值。
好的,我可以帮你写一个 C++ 的程序来实现这个功能。程序如下:
```cpp
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int a[10] = {15, 11, 25, 78, 90, 12, 22, 85, 36, 18};
sort(a, a + 10); // 排序数组
cout << "次小值为:" << a[1] << endl;
cout << "次大值为:" << a[8] << endl;
return 0;
}
```
程序首先定义了一个包含10个元素的整型数组a,并初始化了其值。然后使用sort函数对数组a进行排序,默认从小到大排序。排序后,次小值在数组中的下标为1,次大值在数组中的下标为8(因为数组下标从0开始)。最后输出次小值和次大值即可。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)