题目

演示使用 typedef 关键字为结构体类型创建别名,对比使用别名前后定义结构体变量的语法区别。

输入格式:一行输入两个浮点数,表示二维坐标。

输出格式:输出坐标点的信息。

数据范围与约定:浮点数范围。

思路与算法

1. typedef 别名简化
未定义别名时,必须写完整的 struct Point p;;使用 typedef struct { double x, y; } Point; 声明后,可直接写 Point p;。

2. 工程实践价值
在复杂工程和库开发中,typedef 能让类型名称简短优雅,消除随处可见的 struct 冗余关键字。

完整程序

import java.util.Scanner;

// Java 中通过 class 封装结构类型
class Point2D {
    double x;
    double y;

    public Point2D(double x, double y) {
        this.x = x;
        this.y = y;
    }

    public double distanceTo(Point2D other) {
        double dx = this.x - other.x;
        double dy = this.y - other.y;
        return Math.sqrt(dx * dx + dy * dy);
    }
}

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        double x1 = sc.nextDouble();
        double y1 = sc.nextDouble();
        double x2 = sc.nextDouble();
        double y2 = sc.nextDouble();

        Point2D p1 = new Point2D(x1, y1);
        Point2D p2 = new Point2D(x2, y2);

        System.out.printf("%.2f%n", p1.distanceTo(p2));
    }
}

运行示例

输入:

0 0 6 8

输出:

10.00