1.对于正整数a和b,若a不小于b,则它们的最大公因子gcd(a,b)满足如下递归关系
其中,mod表示模运算,即求余运算。利用该定义,定义并实现一个递归函数,用来计算两个正整数的最大公因子。
#include <stdio.h>
int gcd(int a,int b) {
if(b==0)
return a;
return gcd(b,a%b);
}
2.利用公式
编写一个求正弦函数近似值的函数,结果精确到,实现过程中,不允许调用任何库函数, 但允许调用自已定义并实现的其它函数。
#include <stdio.h>
double sin(int x) {
int n=0;
double flag=999,sum=0,temp=1;
while(flag>1e-5) {
flag=1.0*pow(x,2*n+1)/jc(2*n+1);
sum+=temp*flag;
temp*=-1;
n++;
}
return sum;
}
int pow(int x,int n) {
int final=1;
for(int i=0; i<n; i++)
final*=x;
return final;
}
int jc(int n) {
if(n==0)
return 1;
return n*jc(n-1);
}
int main() {
printf("%lf",sin(1));
}
3.通常用二维数组表示矩阵。编写一个完整程序,在该程序中,定义一个20行10列的二维整型数组,通过键盘输入数据至该数组,输出该数组所对应矩阵的四周边缘元素的平均值。
#include <stdio.h>
double getmean(int **arr,int n,int m) {
int sum=0;
int count=0;
for(int i=0; i<n; i++)
for(int j=0; j<m; j++)
if(i==0||i==n-1||j==0||j==m-1) {
sum+=arr[i][j];
count++;
}
return sum/count*1.0;
}
4.首先,定义一个由整数结点构成的单向链表的结点类型,简要说明如何利用该结点类型表示一个单向链表;其次,定义并实现一个函数,该函数以一个由整数结点构成的单向链表为参数,返回一个新的单向链表,新的单向链表由L中删除所有绝对值为素数的结点后剩余结点构成,并且,各结点中的整数值从链头至链尾按不增顺序排列。
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef struct node {
int key;
struct node *next;
} node;
int isprime(int n) {
if(n<=1)
return 0;
for(int i=2; i<sqrt(n); i++) {
if(n%i==0)
return 0;
}
return 1;
}
struct node *delete(struct node *head) {
struct node *pre=head,*p=head->next;
while(p!=NULL) {
if(isprime(p->key)) {
pre->next=p->next;
struct node *temp=p;
free(temp);
p=pre->next;
} else {
pre=p;
p=p->next;
}
}
return head;
}