练习 03-03-01
输入四个整数,找出其中最大的数。
输出样例:
enter four numbers:
12 34 -4 98
max = 98
please enter four numbers:
58 98 -9 0
max = 98
--------------------------------
Process exited after 11.42 seconds with return value 0
请按任意键继续. . .
方法一:“打擂台算法”
#include<stdio.h>
int main()
{
int a[4],i,max;
printf("enter four numbers:\n");
scanf("%d",&a[0]);
for(i=1;i<4;++i){
scanf("%d",&a[i]);
if(max<a[i]){
max=a[i];
}
}
printf("max = %d",max);
return 0;
}
方法二:函数嵌套
#include<stdio.h>
int max4(int a,int b,int c,int d); //函数的全局声明
int max2(int x,int y);
int main()
{
printf("please enter four numbers:\n");
int a[4],i;
for(i=0;i<4;++i){
scanf("%d",&a[i]);
}
int max=max4(a[0],a[1],a[2],a[3]);
printf("max = %d",max);
return 0;
}
int max2(int x,int y)
{
return(x>y?x:y);
}
int max4(int a,int b,int c,int d)
{
int x,y;
x=max2(a,b);
y=max2(c,d);
return(max2(x,y));
}
方法三(对方法2 的微调)
#include<stdio.h>
int main()
{
int max4(int a,int b,int c,int d);
int a,b,c,d,max;
printf("please enter four numbers:\n");
scanf("%d%d%d%d",&a,&b,&c,&d);
max=max4(a,b,c,d);
printf("max = %d",max);
return 0;
}
int max4(int a,int b,int c,int d)
{
int max2(int x,int y);
int m;
m=max2(a,b);
m=max2(m,c);
m=max2(m,d);
return m;
}
int max2(int x,int y)
{
return(x>y?x:y);
}