题解 | #KiKi设计类继承#

KiKi设计类继承

https://www.nowcoder.com/practice/699ba050e2704591ae3e62401a856b0e

#include<stdio.h>

const float pi=3.14;
struct shapes;

typedef void(*Init)(struct shapes *x); //初始化 
typedef void(*Scanf)(struct shapes *x);//输入值 
typedef void(*Getarea)(struct shapes *x);//获取面积 
typedef void(*Printf)(struct shapes *x);

struct shapes{				//结构体定义 
	int x;
	int y;
	int circle_x;
	int Rec_x;
	double xy_area;
	double circle_area;
	double Rec_area;
	Scanf scanf; 	
	Getarea getarea;  
	Printf print; 
	Init init;
};
void Init_func(struct shapes *x); 
void scanf_func(struct shapes *x);
void getarea_func(struct shapes *x);
void printf_func(struct shapes *x);


void Init_func(struct shapes *x){   //初始化 
	x->circle_x=0;
	x->Rec_x=0;
	x->x=0;
	x->y=0;
	x->xy_area=0;
	x->circle_area=0;
	x->Rec_area=0;
}

void scanf_func(struct shapes *x){		
	int a,b,c,d;
	scanf("%d %d",&a,&b);
	scanf("%d",&c);
	scanf("%d",&d);
	x->x=a;
	x->y=b;
	x->circle_x=c;
	x->Rec_x=d;
}

void getarea_func(struct shapes *x){   //面积计算   xy_area 矩形面积 circle_area 圆面积  Rec_area 正方形面积 
		x->xy_area=x->x*x->y;
		x->circle_area=x->circle_x*x->circle_x*pi;
		x->Rec_area=x->Rec_x*x->Rec_x;
	
}


void printf_func(struct shapes *x){		//	
	if(x->x!=0){
		printf("%g\n",x->xy_area);
	}else if(x->circle_x!=0){
		printf("%g\n",x->circle_area);
	}else if(x->Rec_x!=0){
		printf("%g\n",x->Rec_area);
	}
}




int main(){
	
	//定义 
	struct shapes my_func;
	my_func.init=Init_func;
	my_func.init(&my_func);
	my_func.getarea=getarea_func;
	my_func.scanf=scanf_func;
	my_func.print=printf_func;
	
	//输入 
	my_func.scanf(&my_func);
	my_func.getarea(&my_func);
	
	//结构体 Rectangle1 
	struct shapes  Rectangle1;
	my_func.init(&Rectangle1);
	Rectangle1.x=my_func.x;
	Rectangle1.y=my_func.y;
	Rectangle1.xy_area=my_func.xy_area;
	
	//结构体 Circle
	struct shapes Circle;
	my_func.init(&Circle);
	Circle.circle_x=my_func.circle_x;
	Circle.circle_area=my_func.circle_area;
	
	//Rectangle2
	struct shapes Rectangle2;
	my_func.init(&Rectangle2);	
	Rectangle2.Rec_x=my_func.Rec_x;
	Rectangle2.Rec_area=my_func.Rec_area;
	
	my_func.print(&Rectangle1); 
	my_func.print(&Circle); 
	my_func.print(&Rectangle2); 
	return 0;
}

全部评论

相关推荐

头像
点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务