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;
}