Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C Language Examples - Determining the Maximum Value

C Language Examples - Determining the Maximum Value

C Language Examples C Language Examples

Determine the maximum value from numbers specified by the user.

Example - Determining the maximum value

#include

<

stdio.h

#include

<

stdlib.h

int

main

(

)

{

int

i

,

num

;

float

data

;

printf

(

"

Enter the number of elements (1 ~ 100):

"

)

;

scanf

(

"

%d

"

, &

num

)

;

// Allocate memory for the 'num' elements

data

=

(

float

)

calloc

(

num

,

sizeof

(

float

)

)

;

if

(

data

==

NULL

)

{

printf

(

"

Error!!! Memory was not allocated.

"

)

;

exit

(

0

)

;

}

printf

(

"

\

n

"

)

;

// User input

for

(

i

=

0

;

i

<

num

; ++

i

)

{

printf

(

"

Enter number %d:

"

,

i

1

)

;

scanf

(

"

%f

"

,

data

i

)

;

}

// Loop to find the maximum value

for

(

i

=

1

;

i

<

num

; ++

i

)

{

// To find the minimum value, you can replace < with >

if

(

data

< *

(

data

i

)

)

data

= *

(

data

i

)

;

}

printf

(

"

The largest element = %.2f

"

, *

data

)

;

return

0

;

}

The output is:



输入元素个数(1 ~ 100): 5



输入数字 1: 12

输入数字 2: 32

输入数字 3: 6

输入数字 4: 56

输入数字 5: 21

最大元素 = 56.00

C Language Examples C Language Examples