您的位置:首页 > 其它

C 求字符数组最大值与次大值

2016-01-10 23:27 183 查看
实现代码:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAXSIZE 100

void find_max(char*arr[], int size, char *max, char *second_max)
{
int i;
for ( i = 0; i < size; i++)
{
if (strcmp(max, arr[i]) <= 0)
{
strcpy(second_max, max);
strcpy(max, arr[i]);
}

if (strcmp(second_max, arr[i]) < 0 && strcmp(max, arr[i]) > 0)
{
strcpy(second_max, arr[i]);
}
}
}

void main()
{
char *arr[MAXSIZE];
char *max = NULL;
char *second_max = NULL;
int str_size;
int i;

max = (char*)malloc(sizeof(char)*MAXSIZE);
second_max = (char*)malloc(sizeof(char)*MAXSIZE);
max[0] = '\0';
second_max[0] = '\0';

printf("input string size:\n");
scanf("%d", &str_size);

printf("input %d strings:\n", str_size);
for (i = 0; i < str_size; i++)
{
arr[i] = (char*)malloc(sizeof(char)*MAXSIZE);
fflush(stdin);//清除数据刚进来时缓冲区数据,防止被gets
gets(arr[i]);
}

find_max(arr, str_size, max, second_max);

printf("max = %s, second_max = %s\n", max, second_max);

system("pause");
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: