题目
嵌套结构体:矩形宽高与面积
思路
本题用结构体描述矩形宽高,并写函数求面积。
定义 struct Rect { double w,h; },函数 area(r) 返回 r.w*r.h;读入宽高后打印面积。
解题分析
嵌套结构体成员用 r.tl.x 访问。宽高可取绝对值,坐标先后不影响边长。
完整程序
#include <stdio.h>
#include <math.h>
typedef struct {
double x, y;
} Point;
typedef struct {
Point tl, br;
} Rect;
int main(void)
{
Rect r;
scanf("%lf %lf %lf %lf", &r.tl.x, &r.tl.y, &r.br.x, &r.br.y);
double w = fabs(r.br.x - r.tl.x);
double h = fabs(r.br.y - r.tl.y);
printf("w=%.2f h=%.2f area=%.2f\n", w, h, w * h);
return 0;
}
运行示例
输入:
0 0 4 3输出:
w=4.00 h=3.00 area=12.00