PTA 基础编程题目集 函数题 4-1~4-13

4-1//水题无难点

void PrintN(int N)

{

int i; for(i=1;i<=N;i++)

printf("%d\n",i);

}

4-2//水题无难点

double f( int n, double a[], double x )

{

double sum=0,ans=1;

for(int i=0;i<=n;i++)

{

sum+=a[i]*ans;

ans*=x;

}

return sum;

}

4-3//水题无难点

int Sum ( int List[], int N )

{

int sum=0;

for(int i=0;i

sum+=List[i];

return sum;

}

4-4//水题,精度记得乘一个1.0

ElementType Average( ElementType S[], int N )

{

float ans=0;

for(int i=0;i

ans+=S[i];

ans=ans/(N*1.0);

return ans;

}

4-5//水题,初始定义第一个为最大

ElementType Max( ElementType S[], int N )

{ float max=S[0];

for(int i=1;i

if(max

return max;

}

4-6//水题,可以打表或者直接计算

int FactorialSum( List L )

{

int num[13]={1,1,2,6,24,120,720,5040,40320,362880,3628800,39916800,479001600};

int sum=0;

List p=L;

while(p)

{

sum+=num[p->Data];

p=p->Next;

}

return sum;

}

4-7//水题,先判断是否是平方数,再判断有无相同的数

int IsTheNumber ( const int N )

{

int t=sqrt(N);

if(t*t!=N)return 0;

int num[10];

for(int i=0;i<10;i++)num[i]=0;

int x=N,p=0;

while(x)

{

num[x%10]++;

if(num[x%10]==2)return 1;

x=x/10;

}

return 0;

}

4-8//同4-6

int Factorial( const int N ){

int num[13]={1,1,2,6,24,120,720,5040,40320,362880,3628800,39916800,479001600};

if(N>=0)return num[N];

return 0;

}

4-9//水题记得判断0,0这个点

int Count_Digit ( const int N, const int D )

{

int ans=0,x=N;

if(x<0)x=-N;

while(x)

{

if(x%10==D)ans++;

x=x/10;

}

if(N==0&&D==0)return 1;

return ans;

}

4-10//大数乘法模仿大数加法

#include

void Print_Factorial ( const int N )

{

if(N<0)printf("Invalid input\n");

else if(N>=0&&N<=12)

{

int ans=1;

for(int i=1;i<=N;i++)

ans=ans*i;

printf("%d\n",ans);

}

else

{

char a[3001]="0080207226";

for(int i=14;i<=N;i++)

{

int ans=0,l=strlen(a);

for(int j=0;j

{

int temp=ans;

ans=((a[j]-'0')*i+ans)/10;

a[j]=((a[j]-'0')*i+temp)%10+'0';

}

while(ans)

{

a[strlen(a)]=ans%10+'0';

ans=ans/10;

}

}

for(int i=strlen(a)-1;i>=0;i--)

printf("%c",a[i]);

printf("\n");

}

}

4-11//归并排序,返回A[N/2]

void mer(float A[],float R[],int low,int mid,int hight)

{

int i=low,j=mid+1,k=low;

while(i<=mid&&j<=hight)

{

if(A[i]<=A[j])R[k++]=A[i++];

else R[k++]=A[j++];

}

while(i<=mid)R[k++]=A[i++];

while(j<=hight)R[k++]=A[j++];

for(i=low;i<=hight;i++)

A[i]=R[i];

}

void sort(float A[],float R[],int low,int hight)

{

if(low

{

int mid=(low+hight)/2;

sort(A,R,low,mid);

sort(A,R,mid+1,hight);

mer(A,R,low,mid,hight);

}

}

ElementType Median(ElementType A[], int N )

{

float R[MAXN];

sort(A,R,0,N-1);

return A[N/2];

}

4-12//水题,判断奇偶,位运算

int even( int n )

{

return !(n&1);

}

4-13//标准二分查找,水题

int binSearch(SeqList T, KeyType k)

{

int i=0,j=k;

while(i<=j)

{

int mid=(i+j)/2;

if(T.data[mid].key==k)return mid;

else if(T.data[mid].key>k)j=mid-1;

else i=mid+1;

}

return 0;

}

你可能感兴趣的:(PTA 基础编程题目集 函数题 4-1~4-13)