棋盘格距离
在只能横向或纵向移动的棋盘格道路上,求两点之间的距离。
第一行给出第一个点的坐标 x1 y1,第二行给出第二个点的坐标 x2 y2,都是整数。
输出距离 |x1 − x2| + |y1 − y2|。
两点相同时为 0。
- 输入
- -100,000,000 ≤ x1, y1, x2, y2 ≤ 100,000,000
- 输出
- 一行距离(0 或以上)
1 5 4 1
7
-2 -3 -7 -9
11
在只能横向或纵向移动的棋盘格道路上,求两点之间的距离。
第一行给出第一个点的坐标 x1 y1,第二行给出第二个点的坐标 x2 y2,都是整数。
输出距离 |x1 − x2| + |y1 − y2|。
两点相同时为 0。
1 5 4 1
7
-2 -3 -7 -9
11
运行时这些行会依次作为 input()/标准输入传入(运行中不会等待输入)。
$ 就绪
请在电脑上打开以编写和运行代码。在手机上可以查看题目和题解。
各语言的绝对值函数:Python abs()(内置),JS/TS Math.abs,Java Math.abs,C# Math.Abs,C++ std::abs(整数和浮点都有重载),Craykon 数学.绝对值。
C 按类型用不同的函数——int 用 <stdlib.h> 的 abs,long long 用 llabs,double 用 <math.h> 的 fabs;在 C 中对 long long 用 abs 会被截断成 int。
最常见的陷阱是先把差相加,只取一次绝对值:|(x2 − x1) + (y2 − y1)| 中方向相反的差会互相抵消,第一个样例得到 1 而不是 7。
要对每个差分别取绝对值。
(Java 的 Math.abs(Integer.MIN_VALUE) 会溢出、仍是负数,C# 的 Math.Abs(int.MinValue) 会抛出 OverflowException,但本题每个差最多 2 亿,所以没问题。)
x1, y1 = map(int, input().split())x2, y2 = map(int, input().split())print(abs(x1 - x2) + abs(y1 - y2))const [x1, y1, x2, y2] = require("fs").readFileSync(0, "utf8").trim().split(/\s+/).map(Number);console.log(Math.abs(x1 - x2) + Math.abs(y1 - y2));import { readFileSync } from "node:fs";const [x1, y1, x2, y2]: number[] = readFileSync(0, "utf8").trim().split(/\s+/).map(Number);console.log(Math.abs(x1 - x2) + Math.abs(y1 - y2));import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int x1 = sc.nextInt(), y1 = sc.nextInt(); int x2 = sc.nextInt(), y2 = sc.nextInt(); System.out.println(Math.abs(x1 - x2) + Math.abs(y1 - y2)); }}using System; class Program{ static void Main() { string[] a = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries); string[] b = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries); int x1 = int.Parse(a[0]), y1 = int.Parse(a[1]); int x2 = int.Parse(b[0]), y2 = int.Parse(b[1]); Console.WriteLine(Math.Abs(x1 - x2) + Math.Abs(y1 - y2)); }}#include <cstdlib>#include <iostream> int main() { int x1, y1, x2, y2; std::cin >> x1 >> y1 >> x2 >> y2; std::cout << std::abs(x1 - x2) + std::abs(y1 - y2) << '\n';}#include <stdio.h>#include <stdlib.h> /* 정수 abs()는 stdlib.h, 실수 fabs()는 math.h */ int main(void) { int x1, y1, x2, y2; scanf("%d %d %d %d", &x1, &y1, &x2, &y2); printf("%d\n", abs(x1 - x2) + abs(y1 - y2)); return 0;}a = 控制台.读数字();b = 控制台.读数字();控制台.输出(数学.绝对值(a[0] - b[0]) + 数学.绝对值(a[1] - b[1]));