问题描述
小E正在训练场进行射击练习,靶有10个环,靶心位于坐标(0, 0)。每个环对应不同的得分,靶心内(半径为1)得10分,依次向外的每个环分数减少1分。若射击点在某个半径为i的圆内,则得11-i分。如果射击点超出所有的环,则得0分。
根据给定的射击坐标(x, y),请计算小E的射击得分。
测试样例
样例1:
输入:
x = 1, y = 0
输出:10
样例2:
输入:
x = 1, y = 1
输出:9
样例3:
输入:
x = 0, y = 5
输出:6
样例4:
输入:
x = 3, y = 4
输出:6public class Main { public static int solution(int x, int y) { // 计算射击点到靶心的距离 double distance = Math.sqrt(x * x + y * y);
// 根据距离判断得分
if (distance <= 1) {
return 10;
} else if (distance <= 2) {
return 9;
} else if (distance <= 3) {
return 8;
} else if (distance <= 4) {
return 7;
} else if (distance <= 5) {
return 6;
} else if (distance <= 6) {
return 5;
} else if (distance <= 7) {
return 4;
} else if (distance <= 8) {
return 3;
} else if (distance <= 9) {
return 2;
} else if (distance <= 10) {
return 1;
} else {
return 0;
}
}
public static void main(String[] args) {
System.out.println(solution(1, 0) == 10);
System.out.println(solution(1, 1) == 9);
System.out.println(solution(0, 5) == 6);
System.out.println(solution(3, 4) == 6);
}
}
解题思路
-
计算射击点到靶心的距离:使用欧几里得距离公式计算射击点
(x, y)到靶心(0, 0)的距离。 -
判断得分:根据距离判断射击点在哪个环内,从而确定得分。 public class Main { public static int solution(int x, int y) { // 计算射击点到靶心的距离 double distance = Math.sqrt(x * x + y * y);
// 根据距离判断得分 if (distance <= 1) { return 10; } else if (distance <= 2) { return 9; } else if (distance <= 3) { return 8; } else if (distance <= 4) { return 7; } else if (distance <= 5) { return 6; } else if (distance <= 6) { return 5; } else if (distance <= 7) { return 4; } else if (distance <= 8) { return 3; } else if (distance <= 9) { return 2; } else if (distance <= 10) { return 1; } else { return 0; }}
public static void main(String[] args) { System.out.println(solution(1, 0) == 10); System.out.println(solution(1, 1) == 9); System.out.println(solution(0, 5) == 6); System.out.println(solution(3, 4) == 6); } }
关键步骤解释
- 计算距离:使用
Math.sqrt(x * x + y * y)计算射击点到靶心的距离。 - 判断得分:使用一系列
if-else语句根据距离判断得分。 如何计算射击点与靶心的距离? 计算射击点(x, y)与靶心(0, 0)的距离可以使用欧几里得距离公式。欧几里得距离公式如下:
[ \text{distance} = \sqrt{(x - 0)^2 + (y - 0)^2} ]
简化后即为:
[ \text{distance} = \sqrt{x^2 + y^2} ]
在 Java 中,你可以使用 Math.sqrt 方法来计算平方根,使用 Math.pow 方法来计算平方。
代码示例
public class Main {
public static int solution(int x, int y) {
// 计算射击点到靶心的距离
double distance = Math.sqrt(x * x + y * y);
// 根据距离判断得分
if (distance <= 1) {
return 10;
} else if (distance <= 2) {
return 9;
} else if (distance <= 3) {
return 8;
} else if (distance <= 4) {
return 7;
} else if (distance <= 5) {
return 6;
} else if (distance <= 6) {
return 5;
} else if (distance <= 7) {
return 4;
} else if (distance <= 8) {
return 3;
} else if (distance <= 9) {
return 2;
} else if (distance <= 10) {
return 1;
} else {
return 0;
}
}
public static void main(String[] args) {
System.out.println(solution(1, 0) == 10);
System.out.println(solution(1, 1) == 9);
System.out.println(solution(0, 5) == 6);
System.out.println(solution(3, 4) == 6);
}
}