C语言 最精简的方式,找出3个值中的最大值
时间: 2024-03-06 10:48:59 浏览: 30
可以使用三目运算符(?:)实现:
```c
int max = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c);
```
其中,三目运算符的格式为:
```c
expression1 ? expression2 : expression3
```
当 expression1 为真时,取 expression2 的值,否则取 expression3 的值。因此,上述代码中,如果 a 大于 b,则比较 a 和 c,否则比较 b 和 c,最终得到三个值中的最大值并赋值给变量 max。
相关问题
用c语言从n个数中找出最大值和最小值
以下是用C语言从n个数中找出最大值和最小值的代码示例:
```c
#include <stdio.h>
void calcArray(int arr[], int len, int *max, int *min) {
*max = arr[0];
*min = arr[0];
for (int i = 1; i < len; i++) {
if (arr[i] > *max) {
*max = arr[i];
}
if (arr[i] < *min) {
*min = arr[i];
}
}
}
int main() {
int arr[] = {3, 5, 1, 7, 9, 2};
int len = sizeof(arr) / sizeof(arr[0]);
int max, min;
calcArray(arr, len, &max, &min);
printf("Max value: %d\n", max);
printf("Min value: %d\n", min);
return 0;
}
```
c语言找出一个数组中的最大值的位置
以下是一个示例程序,用于找出一个数组中的最大值及其位置:
```c
#include <stdio.h>
int main() {
int arr[] = {5, 10, 15, 20, 25};
int n = sizeof(arr) / sizeof(arr[0]);
int max = arr[0];
int pos = 0;
for (int i = 1; i < n; i++) {
if (arr[i] > max) {
max = arr[i];
pos = i;
}
}
printf("The maximum value in the array is %d\n", max);
printf("It occurs at position %d\n", pos);
return 0;
}
```
运行结果:
```
The maximum value in the array is 25
It occurs at position 4
```
相关推荐
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)