gpt4 book ai didi

JAVA递归距离伪代码帮助

转载 作者:行者123 更新时间:2023-12-02 08:16:21 25 4
gpt4 key购买 nike

这是我为 JAVA 应用程序编写的伪代码,用于使用坐标计算距离。

totalDistance (int[] x, int[] y, int i)
If x = 1 then
distance = pow(x[i] – x[i – 1], 2) + pow(y[i] – y[i – 1], 2)
return round(sqrt(distance))
else
return round(sqrt(distance)) + totalDistance(x, y, i – 1)

我不太擅长 Java,但我写了下面的内容。当我将变量传递给它时,它崩溃了。

import java.util.Scanner;



class distance {

public static void main(String[] args) {
System.out.println("Welcome to Travel Bliss Distance Calculator!");
Scanner input = new Scanner(System.in);
int[] x = new int[5];
int[] y = new int[5];
String[] city = new String[5];

int i=0;
for (i=0; i < 5;){

System.out.println("Enter X Coordinates>>");
x[i] = input.nextInt();
System.out.println("Enter Y Coordinates>>");
y[i] = input.nextInt();
System.out.println("With Coordinates: (" + x[i] + "," + y[i] + ") ");
i++;
}
totalDistance(x, y, i);
}


public static double totalDistance(int[] x, int[] y, int i){
double distance;
if (i == 1){
distance = pow(x[i] – x[i – 1], 2) + pow(y[i] – y[i – 1], 2);
return distance;
}
else {
return round(sqrt(distance)) + totalDistance(x,y,i-1);
}
}


}

有人知道我做错了什么吗?或者为什么我会崩溃

这是错误>>

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
Syntax error on token "[", Expression expected after this token
distance cannot be resolved to a variable
The type of the expression must be an array type but it resolved to int
Syntax error on token "Invalid Character", [ expected
The type of the expression must be an array type but it resolved to int
Syntax error on token "Invalid Character", [ expected
Syntax error, insert "]" to complete ArrayAccess
Syntax error, insert "]" to complete ArgumentList
The type of the expression must be an array type but it resolved to int
Syntax error on token "Invalid Character", [ expected
The type of the expression must be an array type but it resolved to int
Syntax error on token "Invalid Character", [ expected
Syntax error, insert "]" to complete ArrayAccess
Syntax error, insert "]" to complete ArgumentList
distance cannot be resolved to a variable
Syntax error on token "Invalid Character", invalid AssignmentOperator

at distance.totalDistance(distance.java:30)
at distance.main(distance.java:24)

最佳答案

public static double totalDistance(int[] x, int[] y, int i){
int distance = pow(x[i] – x[i – 1], 2) + pow(y[i] – y[i – 1], 2);
if (x.length == 1){
return distance;
}
else {
return round(sqrt(distance)) + totalDistance(x,y,i-1);
}
}

您需要将返回类型声明为 double 而不是 void。您需要在 if 语句之外声明变量距离。数组永远不会等于整数,我假设您要追求它的大小。

你的逻辑仍然有一些错误,但我不想为你做所有的作业。

关于JAVA递归距离伪代码帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6351603/

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