入门客AI创业平台(我带你入门,你带我飞行)
博文笔记

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

创建时间:2016-01-10 投稿人: 浏览次数:980

实现代码:

#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] = "";
    second_max[0] = "";

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

    printf("input %d strings:
", 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
", max, second_max);

    system("pause");
}

这里写图片描述

声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。