2在一个一维整型数组中找出其中最大的数及其下标。c语言
时间: 2024-02-09 15:11:26 浏览: 51
可以使用一个循环遍历整个数组来找出最大值及其下标,代码如下:
```c
#include <stdio.h>
int main() {
int arr[] = {2, 5, 8, 3, 9, 1};
int max = arr[0]; // 假设最大值为数组的第一个元素
int maxIndex = 0; // 假设最大值下标为0
for (int i = 1; i < sizeof(arr)/sizeof(int); i++) {
if (arr[i] > max) {
max = arr[i]; // 更新最大值
maxIndex = i; // 更新最大值下标
}
}
printf("最大值为 %d,下标为 %d\n", max, maxIndex);
return 0;
}
```
输出结果为:
```
最大值为 9,下标为 4
```
相关问题
用c语言写出从键盘输入含有10个元素的一维整型数组,找出最大和最小数并调换位置
以下是用 C 语言写出从键盘输入含有 10 个元素的一维整型数组,找出最大和最小数并调换位置的代码:
```c
#include <stdio.h>
int main() {
int arr[10];
int i, max_index, min_index, temp;
// 从键盘输入数组元素
printf("请输入含有 10 个元素的一维整型数组:\n");
for (i = 0; i < 10; i++) {
scanf("%d", &arr[i]);
}
// 找出最大和最小数的下标
max_index = min_index = 0;
for (i = 1; i < 10; i++) {
if (arr[i] > arr[max_index]) {
max_index = i;
}
if (arr[i] < arr[min_index]) {
min_index = i;
}
}
// 调换最大和最小数的位置
temp = arr[max_index];
arr[max_index] = arr[min_index];
arr[min_index] = temp;
// 输出调换后的数组
printf("调换后的数组为:\n");
for (i = 0; i < 10; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
```
如果您有其它问题,欢迎继续提问。
用c语言写一个从键盘输入含有10个元素的一维整型数组,找出最大和最小数并调换位置的程序
下面是用 C 语言编写的程序,可以从键盘输入含有 10 个元素的一维整型数组,找出最大和最小数并调换位置:
```c
#include <stdio.h>
int main() {
int arr[10];
int i, max_index, min_index, temp;
printf("请输入 10 个整数:\n");
for (i = 0; i < 10; i++) {
scanf("%d", &arr[i]);
}
max_index = min_index = 0;
for (i = 1; i < 10; i++) {
if (arr[i] > arr[max_index]) {
max_index = i;
}
if (arr[i] < arr[min_index]) {
min_index = i;
}
}
temp = arr[max_index];
arr[max_index] = arr[min_index];
arr[min_index] = temp;
printf("调换后的数组为:\n");
for (i = 0; i < 10; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
```
这个程序首先定义了一个长度为 10 的整型数组 `arr`,然后通过循环从键盘输入 10 个整数,存储到数组中。接着,程序遍历数组,找出最大值和最小值的下标,然后交换这两个元素的位置。最后,程序输出调换后的数组。
相关推荐
![](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://img-home.csdnimg.cn/images/20210720083646.png)
![xlsx](https://img-home.csdnimg.cn/images/20210720083732.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)