相同复数查询——查询函数+函数指针

 1、不分离查询函数,不使用函数指针

#include<stdio.h>
#include<math.h>
#include<stdbool.h>
typedef struct complex
{
	float e1,e2;  //实部,虚部
} Com; //建立复数结构体

bool compare(Com c1,Com c2)  //比较实部和虚部是否相等
{
	return(c1.e1==c2.e1 && c1.e2==c2.e2);
}

int main()  
{
	Com a[20],e;  //e为结构体类型
	int i,n;
	printf("Input the length:");
	scanf("%d",&n);
	for(int i=0;i<n;i++){
		scanf("%f%f",&a[i].e1,&a[i].e2);  //输入实部和虚部
	}
	printf("Input e:\n");
	scanf("%f %f",&e.e1,&e.e2);  //输入比较的实部和虚部
	i=0;
	while(i<n && !compare(a[i],e)){  //进行对比相同时i++
		i++;
	}
	
	if(i<n){
		printf("The position is %d\n",i+1); //输出位置
	}
	else 
	printf("Not found!");  //否则为找不到
	return 0;
}

2、分离查询函数,使用函数指针

在定义函数指针时要定义指针类型和输入数值类型;并且要将指针指向函数

#include<stdio.h>
#include<math.h>
#include<stdbool.h>
typedef struct complex
{
	float e1,e2;  //实部,虚部
} Com; //建立复数结构体

bool compare(Com c1,Com c2)  //比较实部和虚部是否相等
{
	return(c1.e1==c2.e1 && c1.e2==c2.e2);
}

int search(Com a[],int n,Com e,bool (*fp)(Com,Com)) //使用函数指针
{
	int i=0;
	while(i<n && !(*fp)(a[i],e)) 
		i++;
	
	if(i<n)
		return i+1;
	else 
		return 0;
}

int main()  
{
	Com a[20],e;  //e为结构体类型
	int i,n;
	bool (*fp)(Com,Com); //定义bool型函数指针
	printf("Input the length:");
	scanf("%d",&n);
	for(int i=0;i<n;i++){
		scanf("%f%f",&a[i].e1,&a[i].e2);  //输入实部和虚部
	}
	printf("Input e:\n");
	scanf("%f %f",&e.e1,&e.e2);  //输入比较的实部和虚部
	
	fp=compare;  //函数指针指向函数compare
	
	i=search(a,n,e,compare);  //传入结构体和函数(只需传入名称)
	
	if(i)
		printf("The position is %d\n",i);
	else 
		printf("Not found!\n");
	return 0;
}

  • 9
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值