问题描述
import java.lang.Math;
import java.awt.*
public class Triangle implements Shape
{
java.awt.Point a;
java.awt.Point b;
java.awt.Point c;
public Triangle(java.awt.Point a, java.awt.Point b, java.awt.Point c)
{
this.a = a;
this.b = b;
this.c = c;
}
public double getArea( )
{
double area;
return area = Math.abs((a-c)*(b-a)-(a-b)*(c-a));
} ...
http://upload.wikimedia.org/math/f/e/5/fe56529cdaaaa9bb2f71c1ad8a1a454f.png
我正在尝试从 2D 笛卡尔坐标系中的 3 个点 (x,y) 计算三角形的面积.我假设我上面的公式正确地产生了三角形的面积(如果没有,请纠正我)但我的编译器说运算符 - 不能应用于 java.awt.Point,java.awt.Point".我假设它是这样说的,因为你不能相互减去点,但公式中的每个值都是 x 或 y 值,而不是一个点.我怎样才能修复我的代码,这样才能正常工作?谢谢!
I am trying to calculate the area of a triangle from 3 points (x,y) from a 2D Cartesian coordinate system. I'm assuming that my above formula correctly yields the area of a triangle (if not, please correct me) but my compiler says "operator - cannot be applied to java.awt.Point,java.awt.Point". I'm assuming it's saying this because you cannot subtract points from each other, but each value in the formula is either an x or y value, not a point. How can I fix my code so this would work?Thanks!
推荐答案
根据维基百科,你公式正确.文章包含大量有用且清晰的数据.
根据 java.awt.point 文档,你应该使用 getX()
和 getY()
方法,它们返回一个点的坐标值.
According to Wikipedia, you formula is correct. The article contains lots of useful and clear data.
According to the java.awt.point documentation, you should use the getX()
and getY()
methods, which return the coordinate value of a point.
也就是说,
应表示为:
Math.abs((a.getX()-c.getX())*(b.getY()-a.getY())-
(a.getX()-b.getX())*(c.getY()-a.getY()))*0.5;
使用 point.x
可能不是一个好习惯,因为如果你有一个 getter 方法,你不应该访问一个对象的变量.这是接口和实现分离的一方面:数据point.x
可能以多种形式存储,而不仅仅是int
;接口方法确保您每次使用它时都会得到一个 int.
It is probably not such a good practice to use point.x
, because you shouldn't access an object's variable if you have a getter method that does that. This is the one aspect of separation between interface and implementation: the data point.x
might be stored in many forms, not just int
; The interface method assures that you'll get an int every time you use it.
这篇关于Java:计算三角形的面积的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!