zl程序教程

您现在的位置是:首页 >  其它

当前栏目

例 6.9 有3个字符串,要求找出其中最大者。

字符串 要求 找出 其中 6.9
2023-09-14 09:06:59 时间

C程序设计(第四版) 谭浩强 例6.9 个人设计

例 6.9 有3个字符串,要求找出其中最大者。

代码块:

方法1

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
	char m[3][50], max[50];
	for (int i=0; i<3; gets(m[i]), i++);
	strcmp(m[0], m[1])>0?strcpy(max, m[0]):strcpy(max, m[1]);
	strcmp(m[2], max)>0?strcpy(max, m[2]):strcpy(max, max);
	printf("Max=%s\n", max);
	system("pause");
	return 0;
}

方法2:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void input(char **s, int nu);
void max(char **s, int nu);
int main()
{
	char **p=(char**)malloc(3*sizeof(char*));
	int i;
	for(i=0; i<3; i++)
		p[i]=(char*)malloc(20*sizeof(char));
	input(p, 3);
	max(p, 3);
	system("pause");
	return 0;
}
void input(char **s, int nu)
{
	int i;
	char **p;
	for(i=0, p=s; i<nu; i++, p++){
		printf("Enter No.%d string: ", i+1);
		gets(*p);
	}
}
void max(char **s, int nu)
{
	char **p, *max=*s;
	for(p=s; p<s+nu; p++)
		if(strcmp(*p, max)>0)
			strcpy(max, *p);
	printf("max=");
	puts(max);
}