如何在c语言中编写一段可以提取(-5,6,7,7,13, 100, 20, -300, 1000 ,-1)这十个整数中最大值的代码,运用int *find_largest(int a[], int n);
时间: 2024-05-01 12:17:05 浏览: 16
以下是在c语言中编写一段可以提取(-5,6,7,7,13, 100, 20, -300, 1000 ,-1)这十个整数中最大值的代码,运用int *find_largest(int a[], int n):
```c
#include <stdio.h>
int *find_largest(int a[], int n);
int main() {
int arr[] = {-5, 6, 7, 7, 13, 100, 20, -300, 1000, -1};
int *largest = find_largest(arr, 10);
printf("The largest number is: %d\n", *largest);
return 0;
}
int *find_largest(int a[], int n) {
int i;
int *largest = &a[0];
for (i = 1; i < n; i++) {
if (a[i] > *largest) {
largest = &a[i];
}
}
return largest;
}
```
在这段代码中,我们首先定义了一个整数数组`arr`,其中包含了10个整数。接着,我们调用了`find_largest`函数,并将`arr`数组和10作为参数传递给它。这个函数会返回指向最大值的指针。我们将这个指针存储在`largest`指针变量中,并使用`*largest`来访问最大值。最后,我们在屏幕上打印出最大值。
在`find_largest`函数中,我们首先定义了一个指针变量`largest`,并将它指向数组中的第一个元素。然后,我们使用`for`循环遍历数组中的所有元素。如果当前元素的值比`largest`指向的元素的值要大,我们就更新`largest`指针的值。最后,我们返回指向最大值的指针。