最大值问题。为一维数组输入10个整数,输出其最大值及其在数组中的位置。用c语言
时间: 2024-05-13 14:18:10 浏览: 22
以下是使用C语言解决该问题的示例代码:
```c
#include <stdio.h>
int main() {
int arr[10], max = arr[0], pos = 0;
printf("请输入10个整数:\n");
for (int i = 0; i < 10; i++) {
scanf("%d", &arr[i]);
if (arr[i] > max) {
max = arr[i];
pos = i;
}
}
printf("最大值为:%d,位置为:%d\n", max, pos);
return 0;
}
```
首先定义一个长度为10的整数数组`arr`,然后通过`for`循环依次读取10个整数,并将其中的最大值及其在数组中的位置记录下来。最后输出最大值及其位置。
相关问题
C语言:编写一个程序,实现将一维数组中的最大值和最小值对换位置。主函数中为一维数组输入10哥整数,并输出结果
好的,以下是您所需的 C 代码:
```c
#include <stdio.h>
void swap(int *a, int *b) { // 交换函数
int temp = *a;
*a = *b;
*b = temp;
}
void swapMaxMin(int arr[], int n) { // 交换最大值和最小值位置的函数
int maxIndex = 0, minIndex = 0;
for (int i = 1; i < n; i++) {
if (arr[i] > arr[maxIndex]) {
maxIndex = i;
}
if (arr[i] < arr[minIndex]) {
minIndex = i;
}
}
swap(&arr[maxIndex], &arr[minIndex]);
}
int main() {
int arr[10];
printf("请输入10个整数:\n");
for (int i = 0; i < 10; i++) {
scanf("%d", &arr[i]);
}
swapMaxMin(arr, 10);
printf("交换后的数组为:\n");
for (int i = 0; i < 10; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
```
注意:由于题目要求是将最大值和最小值对换位置,因此我们需要先找到数组中的最大值和最小值的下标,然后再用一个交换函数来实现它们的位置对换。
用c语言写,输入10个数存入一维数组中,输出其中的最大值
好的,以下是用C语言编写的程序,可以实现输入10个数存入一维数组中,并输出其中的最大值:
```c
#include <stdio.h>
int main() {
int nums[10]; // 定义一个长度为10的整型数组
int i, max;
printf("请输入10个整数:\n");
// 循环读入10个整数
for (i = 0; i < 10; i++) {
scanf("%d", &nums[i]);
}
// 假设第一个数为最大值
max = nums[0];
// 循环比较每个数,找出最大值
for (i = 1; i < 10; i++) {
if (nums[i] > max) {
max = nums[i];
}
}
printf("最大值为:%d\n", max);
return 0;
}
```
运行程序后,输入10个整数,程序会输出其中的最大值。