笛卡尔斜率计算误差Java

时间:2013-10-18 10:10:43

标签: java cartesian cartesian-coordinates

我在Java中使用笛卡尔斜率计算时遇到了一些麻烦。 因此,我的源代码允许您输入4个数字x1 y1 x2 y2,它们代表笛卡尔坐标系中2个点的2个坐标。

然后我通过计算deltaX和deltaY来计算斜率。 因此,如果您得到十分之一的数字,我会使用双精度进行斜率计算(deltaY / deltaX)

然后我使用IF函数说:if slope = 0 --> println("not a linear line")。否则计算X和Y极的交叉点并打印结果

所以这就是问题:如果斜率为0(例如x1:0 y1:1 x2:0 y2:9)那么我得到一个错误:Exception in thread main java.lang.ArithmeticException: / by zero


这是完整的脚本:

import java.io.*;

public class Cartesian
{
    public static int leesIn(String var, BufferedReader in) throws IOException
    {
        System.out.println("type een getal in die " + var + " moet voorstellen.");
        return Integer.parseInt(in.readLine());
    }
    public static void main(String[] args) throws IOException
    {


    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

    int x1, x2, y1, y2;
    x1 = leesIn("X1", in);
    y1 = leesIn("Y1", in);
    x2 = leesIn("X2", in);
    y2 = leesIn("Y2", in);

    System.out.println("The Coördinates of point 1 is: (" + x1 + ", " + y1 + "). The Coördinates of point 2 is: (" + x2 + ", " + y2 + ").");


    int deltaY = y2 - y1;
    int deltaX = x2 - x1;
    double RC = deltaY / deltaX;

    if ((RC) == 0)
    {
        System.out.println("The slope is 0, no linear line.");
    }else
    {
        System.out.println("The slope is: " + RC);
        double B = y1-(RC*x1);
        System.out.println("The crosspoint with Y, if x is 0, : " + B);
    }
}
}

任何人都知道如何解决我的问题? tnx提前!

3 个答案:

答案 0 :(得分:1)

尝试捕获块

double RC;
try{
  RC = deltaY / deltaX;

}

catch(ArithmeticException ex){
System.out.println("Not a Linear Line");

}

答案 1 :(得分:1)

您应该将计算移动到您确定可以计算的区域(在您的情况下double RC = deltaY / deltaX;

所以你的代码将是:

int deltaY = y2 - y1;
int deltaX = x2 - x1;

if (deltaY == 0)
{
    System.out.println("The slope is 0, no linear line.");
}else if (deltaX == 0)
{
    System.out.println("Not a Linear Line");
}else
{
    double RC = (double) deltaY / deltaX;
    System.out.println("The slope is: " + RC);
    double B = y1-(RC*x1);
    System.out.println("The crosspoint with Y, if x is 0, : " + B);
}

答案 2 :(得分:0)

试试这个

try {

  double RC = deltaY / deltaX;

  if ((RC) == 0)
  {
    System.out.println("The slope is 0, no linear line.");
  }else
  {
    System.out.println("The slope is: " + RC);
    double B = y1-(RC*x1);
    System.out.println("The crosspoint with Y, if x is 0, : " + B);
  }
} catch(ArithmeticException ae) {
    System.out.println("Not a linear line");
}