我有一個陣列。
int a[6] = {3, 4, 1, 2, 5, 6}
我想通過使用預定義的C函式找到最小和最大的元素,如果有的話?請幫助我們
uj5u.com熱心網友回復:
不,沒有標準的C函式。但你可以自己做這個
int max = arr[0] 。
for (i = 1; i < n; i )
if (arr[i] > max)
max = arr[i]。
從if里面的比較可以看出是大還是小。如果>,是大。如果<,是小
。uj5u.com熱心網友回復:
不,在標準庫中沒有一個minmax函式,但是你可以自己創建一個
示例:
#include <limit.h>
#include <stddef.h>
#include <stdio.h>
//a struct to hold the min and max result[/span].
typedef struct {
int min;
int max;
} mm;
//a function to find the min and max values[/span].
mm minmax(const int *arr, size_t len) /span> {
mm res = {INT_MAX, INT_MIN}; //以min = INT_MAX, max = INT_MIN開始。
for(const int *end = arr len; arr != end; arr) {
if(*arr < res.min) res.min = *arr;
if(*arr > res.max) res.max = *arr;
}
return res;
}
int main() {
int a[6] = {3, 4, 1, 2, 5, 6}。
mm res = minmax(a, sizeof a / sizeof *a) 。
printf("min: %d max: %d
", res.min, res.max)。)
}
uj5u.com熱心網友回復:
C99包含math.h。
這里面有一些函式 - fmin, fmax, fminl, fmaxl, fmaxf, fminf
#include <math.h>
double fmin( double x, double y ) /span>。
float fminf( float x, float y ) /span>;
long double fminl( long double x , long double y )。
fmin()函式回傳較小引數的值。
#include <math.h>
double fmax( double x, double y ) /span>。
float fmaxf( float x, float y ) /span>;
long double fmaxl( long double x 。long double y )。
fmax()函式回傳較大引數的值。
所以,對于答案--
float max=0。
for (i = 0; i < n; i )
max = fmaxf (max, arr[i])。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/322231.html
標籤:
