// 核心函数的实现
ElementType Max(ElementType array[], int N)
{
ElementType max = array[0]; // 初始化变量的值
for (int cnt = 1; cnt < N; ++cnt)
{
if (max < array[cnt])
{
max = array[cnt]; // 求得最大值
}
}
return max;
}
本题要求实现一个函数,求N
个集合元素S[]
中的最大值,其中集合元素的类型为自定义的ElementType
。
函数接口定义:
ElementType Max( ElementType S[], int N );
其中给定集合元素存放在数组S[]
中,正整数N
是数组元素个数。该函数须返回N
个S[]
元素中的最大值,其值也必须是ElementType
类型。
完整的可执行代码(可以直接在本地编译并运行):
#include <stdio.h> // 预处理语句
#define MAX_NUMBER 10 // 符号常量的定义
typedef float ElementType; // 自定义类型的定义
ElementType Max(ElementType array[], int N); // 函数的声明
int main(void) // 主函数
{
ElementType array[MAX_NUMBER] = {0}; // 保持初始化变量的编程习惯
int N = 0; // 同上
scanf("%d", &N); // 输入函数
for (int idx = 0; idx < N; ++idx)
{
scanf("%f", &array[idx]); // 输入函数
}
printf("%.2f\n", Max(array, N)); // 输出函数
return 0;
}
// 核心函数的实现
ElementType Max(ElementType array[], int N)
{
ElementType max = array[0]; // 初始化变量的值
for (int cnt = 1; cnt < N; ++cnt)
{
if (max < array[cnt])
{
max = array[cnt]; // 求得最大值
}
}
return max;
}
输入样例:
3
12.3 34 -5
输出样例:
34.00