题目
定义包含左上角坐标与宽高属性的嵌套结构体 Rectangle,计算并输出该矩形的面积与周长。
输入格式:一行输入两个浮点数,分别表示矩形的宽度 w 和高度 h。
输出格式:按格式输出矩形的面积与周长(保留两位小数)。
数据范围与约定:w, h > 0。
思路与算法
1. 复合结构嵌套
结构体内部可以嵌套另一个结构体作为成员变量(例如 Point topleft 成员)。
2. 多级成员访问
使用点操作符逐级访问内部结构体成员,如 rect.topleft.x;面积直接用 rect.w * rect.h 计算。
完整程序
import java.util.Scanner;
class Rectangle {
double x;
double y;
double w;
double h;
public Rectangle(double x, double y, double w, double h) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
}
public double area() {
return w * h;
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double x = sc.nextDouble();
double y = sc.nextDouble();
double w = sc.nextDouble();
double h = sc.nextDouble();
Rectangle rect = new Rectangle(x, y, w, h);
System.out.printf("w=%.2f h=%.2f area=%.2f%n", rect.w, rect.h, rect.area());
}
}运行示例
输入:
0 0 4 3输出:
w=4.00 h=3.00 area=12.00