编一个递归函数,求给定数组A中的最大元素。假设数组A是含有100个整数的数组。
解题思路:
递归入门
递归很难想,用分治的思想,能列出通式就能用递归
代码如下:
#include<stdio.h>
int maxx(int a[],int n)
{
if(n==1)
{
return a[0];
}
int t=maxx(a+1,n-1);
if(a[0]>t)
{
return a[0];
}
else return t;
}
int main()
{
int a[100]={
1,32,456,543,546,235435,545234,-9,0,0,
0,0,0,0,0,0,0,0,0,0,
1,32,456,543,546,235435,545234,-9,0,0,
0,0,0,0,0,0,0,0,0,0,
1,32,456,543,546,235435,545234,-9,0,0,
0,0,0,0,0,0,0,0,0,0,
1,32,456,543,546,235435,545234,-9,0,0,
0,0,0,0,0,0,0,0,0,0,
1,32,456,543,546,235435,545234,-9,0,0,
0,0,0,0,0,0,0,0,0,0
};
printf("%d\n",maxx(a,100));
return 0;
}
tbtbtb求n个数的平均值
#include<stdio.h>
double a[3];
double aver(double a[],int n)
{
if(n==1) return a[0];
double t=aver(a+1,n-1);
double ans=(a[0]+t*(n-1))/n;
return ans;
}
int main()
{
for(int i=0;i<3;i++)
{
scanf("%lf",&a[i]);
}
for(int i=0;i<3;i++)
{
printf("%f ",a[i]);
}
printf("%.3f\n",aver(a,3));
return 0;
}
/*
1.1 2.2 3.3
*/