gpt4 book ai didi

java - 出现错误 : possible lossy conversion from double to int. ...但我没有使用任何 double ?

转载 作者:行者123 更新时间:2023-11-30 02:38:44 25 4
gpt4 key购买 nike

我已经做了很多研究,我确信这只是一件愚蠢的事情,所以我提前道歉。我正在尝试 CodinGame 挑战,我正在使用这批代码。

class Player {

public static void main(String args[]) {
Scanner in = new Scanner(System.in);

// game loop
while (true) {
int x = in.nextInt();
int y = in.nextInt();
int nextCheckpointX = in.nextInt(); // x position of the next check point
int nextCheckpointY = in.nextInt(); // y position of the next check point
int nextCheckpointDist = in.nextInt(); // distance to the next checkpoint
int nextCheckpointAngle = in.nextInt(); // angle between your pod orientation and the direction of the next checkpoint
int opponentX = in.nextInt();
int opponentY = in.nextInt();
int distX = Math.abs(x - nextCheckpointX);
int distY = Math.abs(y - nextCheckpointY);
int distance = Math.sqrt(distX * distX + distY * distY);

它走得更远,但最后一行是我遇到问题的地方。我已经注释掉了我的其余代码,以确保这是发生错误的地方。

现在,我知道如果我取一个 int 的平方根,我有可能得到一个 double,但如果我将变量设置为一个 int,那么它应该只存储为一个 int……对吗?我什至尝试将它存储为 double 或浮点数(无论如何我都不想要),但它仍然给我这个错误。我究竟做错了什么?

最佳答案

Math.sqrt()返回 double ,因此您需要将结果转换为 (int)明确地告诉编译器您了解可能会丢失信息。毕竟,如果结果是2.125 ,你最终会得到 2在您的 int多变的。编译器只是确保您理解这一点,而不是默默地删除小数部分。

因此添加显式转换

int distance = (int) Math.sqrt(distX * distX + distY * distY);

请记住,类型转换 6.99int不四舍五入到 7 ,它会将其截断为 6 ,这可能不是你想要的。见 Math.round()用于四舍五入的值。

关于java - 出现错误 : possible lossy conversion from double to int. ...但我没有使用任何 double ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42375861/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com