java - 通过使用多种方法,找到具有给定坐标的三角形的周长
问题描述
import java.util.Scanner;
public class Perimeter {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter X1: ");
double X1 = scan.nextDouble();
System.out.println("Please enter Y1: ");
double Y1 = scan.nextDouble();
System.out.println("Please enter X2: ");
double X2 = scan.nextDouble();
System.out.println("Please enter Y2: ");
double Y2 = scan.nextDouble();
System.out.println("Please enter X3: ");
double X3 = scan.nextDouble();
System.out.println("Please enter Y3: ");
double Y3 = scan.nextDouble();
finddistance(X1,Y1,X2,Y2,X3,Y3);
double answer = triperimeter(base1, base2, base3);
System.out.println(answer);
}
public static finddistance(double X1, double Y1, double X2, double Y2, double X3, double Y3){
double base1 = Math.sqrt(Math.pow((X2 - X1),2) + Math.pow((Y2 - Y1),2));
double base2 = Math.sqrt(Math.pow((X3 - X1),2) + Math.pow((Y3 - Y1),2));
double base3 = Math.sqrt(Math.pow((X3 - X2),2) + Math.pow((Y3 - Y2),2));
}
public static double triperimeter(double base1, double base2, double base3){
return (double) base1 + base2 + base3;
}
}
我们现在正在学习如何使用多种方法编写代码,我认为我的错误如下:
在方法 finddistance 中,我需要以某种方式与此代码中的所有方法共享/返回变量 base123,但我不知道该怎么做。
当我编译这段代码时,它只会给我一个错误消息:无效的方法声明,需要返回类型。在公共静态 finddistance 线上。
解决方案
我怀疑你的老师想要的是有一种findDistance
方法,只计算一个距离,但你调用了 3 次。然后,当您计算出三个长度时,如果您愿意,可以将它们全部添加到单独的方法中。
另请注意,通常更准确地使用Math.hypot
代替Math.sqrt
andMath.pow
一起使用。
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter Ax: ");
double ax = scan.nextDouble();
System.out.println("Please enter Ay: ");
double ay = scan.nextDouble();
System.out.println("Please enter Bx: ");
double bx = scan.nextDouble();
System.out.println("Please enter By: ");
double by = scan.nextDouble();
System.out.println("Please enter Cx: ");
double cx = scan.nextDouble();
System.out.println("Please enter Cy: ");
double cy = scan.nextDouble();
double lengthA = findDistance(bx, by, cx, cy);
double lengthB = findDistance(ax, ay, cx, cy);
double lengthC = findDistance(ax, ay, bx, by);
double answer = perimeter(lengthA, lengthB, lengthC);
System.out.println(answer);
}
public static double findDistance(double x1, double y1, double x2, double y2){
return Math.hypot( x2 - x1, y2 - y1 );
}
public static double perimeter(double length1, double length2, double length3) {
return length1 + length2 + length3;
}
推荐阅读
- python - numpy中获得n对距离的最快方法
- android - 具有 SavedStateHandle 的 ViewModel - 反序列化具有自定义数据类的 LiveData 时出现异常
- python - 如何将对象转换为在熊猫中浮动
- vue.js - 如何使用 VueJS 创建和销毁组件数据?
- typescript - 如何将辅助方法添加到 typeORM 实体?
- mysql - Mysql:在更新查询中使用嵌套选择查询会产生死锁
- python - Python:df['Col'].apply(lambda row: len(row)) 和 df.apply(lambda row: len(row['Col']), axis=1) 有什么区别?
- arduino - 无法在 Arduino IDE 中编辑示例草图
- java - 在春季进行改造调用时,当状态码不是 200 时,响应正文为空
- c++ - scanf 用于字符和整数