高级语言期末2005级A卷(计算机学院)

本文介绍了C语言中的四个编程示例:使用辗转相除法判断两个整数是否互质,查找并打印所有三位Armstrong数,实现递归二分搜索以及设计一个数据类型来表示整数并比较任意两个整数的大小。
摘要由CSDN通过智能技术生成

1.编写函数,判断两个整数是否互质,其中求两个正整数M、N的最大公约数使用辗转相除法

#include <stdio.h>
 
int prime(int m, int n) {
    int temp;
    while (n != 0) {
        temp = m % n;
        m = n;
        n = temp;
    }
    if (m == 1)
        return 1;
    else
        return 0;
}
 
int main() {
    printf(prime(50, 2) ? "Yes" : "No");
    return 0;
}

2.编程序,打印所有三位的Armstrong数,所谓Armstrong数是指其值等于它本身每位数字立方和的数。

#include <stdio.h>

int armstr(int n) {
	int sum=0;
	int flag=n;
	while(n>0) {
		sum+=pow(n%10,3);
		n/=10;
	}
	if(flag==sum)
		return 1;
	return 0;
}
int main() {
	printf("%d",armstr(152));
}

3.编写一个递归函数,实现在已递增排序的整数数组中进行二分检索

#include <stdio.h>
 
int search(int *a,int left,int right,int key) {
	while(left<=right) {
		int mid=(left+right)/2;
		if(a[mid]==key)
			return mid;
		else if(a[mid]<key)
			return (a,mid+1,right,key);
		return(a,left,mid-1,key);
	}
	return -1;
}

4.一个整数可以表示成图一的形式(符号有两种可能:+,-)
①设计这种表示法的数据类型。②并编写函数判断任意给定两个整数的大小

#include <stdio.h>
#include <stdlib.h>

typedef struct List {
	int sign;
	int len;
	struct node *next;
} List;

typedef struct node {
	int key;
	struct node *next;
} node;

int compare(struct List *a,struct List *b) {
	if(a->sign==1&&b->sign==-1)
		return 1;
	if(a->sign==-1&&b->sign==1)
		return -1;
	if(a->sign==-1&&b->sign==-1) {
		if(a->len>b->len)
			return -1;
		else if(a->len<b->len)
			return 1;
	}
	if(a->sign==1&&b->sign==1) {
		if(a->len<b->len)
			return -1;
		else if(a->len>b->len)
			return 1;
	}
	struct node *p=a->next,*q=b->next;
	while(p!=NULL&&q!=NULL) {
		if(p->key>q->key) {
			if(a->sign==-1&&b->sign==-1)
				return -1;
			if(a->sign==1&&b->sign==1)
				return 1;
		} else if(p->key<q->key) {
			if(a->sign==-1&&b->sign==-1)
				return 1;
			if(a->sign==1&&b->sign==1)
				return -1;
		}
		p=p->next;
		q=q->next;
	}
	return 0;
}
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值