c语言中找一维数组最小的元素值及其序列号怎么做
时间: 2024-05-02 10:19:28 浏览: 22
可以使用循环遍历一维数组,利用一个变量记录最小值及其序列号,比较每个元素与当前最小值的大小,若小于当前最小值,则更新最小值和序列号。以下是示范代码:
```c
#include <stdio.h>
int main() {
int arr[10] = {3, 5, 2, 8, 1, 9, 4, 7, 6, 0};
int size = sizeof(arr) / sizeof(arr[0]);
int min_val = arr[0], min_idx = 0;
for (int i = 1; i < size; i++) {
if (arr[i] < min_val) {
min_val = arr[i];
min_idx = i;
}
}
printf("The minimum value is %d and its index is %d\n", min_val, min_idx);
return 0;
}
```
当然,还有其他方法可以实现此功能,如使用指针、使用库函数等。
相关问题
用c语言求二维数组中最大元素值及其行列号
可以使用以下代码实现:
```c
#include <stdio.h>
int main() {
int matrix[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
int max = matrix[0][0];
int row = 0, col = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
if (matrix[i][j] > max) {
max = matrix[i][j];
row = i;
col = j;
}
}
}
printf("Max value = %d, Row = %d, Column = %d\n", max, row+1, col+1);
return 0;
}
```
这里假设二维数组是一个 3 行 4 列的矩阵,可以根据实际情况进行修改。首先将二维数组中第一个元素设为最大值,然后遍历整个数组,如果遇到比最大值更大的元素,就更新最大值和行列号。最后输出最大值和行列号即可。注意,行列号从 1 开始计数,因为人们习惯从 1 开始计数。
用c语言编写求二维数组中元素的最大值和最小值的程序
以下是用C语言编写求二维数组中元素的最大值和最小值的程序:
```c
#include <stdio.h>
#define ROWS 3
#define COLS 4
int main()
{
int matrix[ROWS][COLS] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
int max = matrix[0][0]; // 初始化为第一个元素
int min = matrix[0][0]; // 初始化为第一个元素
// 遍历二维数组,找到最大值和最小值
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
if (matrix[i][j] > max) {
max = matrix[i][j];
}
if (matrix[i][j] < min) {
min = matrix[i][j];
}
}
}
printf("最大值为:%d,最小值为:%d\n", max, min);
return 0;
}
```
运行结果:
```
最大值为:12,最小值为:1
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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)