简体   繁体   English

为什么 println 在 for 循环中只打印一次并且输出错误的值?

[英]Why is println in a for loop printing just once and the wrong value?

I have to create a code that, given the polygon name and its vertex coordinates, prints the perimeter.我必须创建一个代码,给定多边形名称及其顶点坐标,打印周长。 Even if I change the input values, it always print 5.0.即使我更改输入值,它也始终打印 5.0。 What am I doing wrong?我究竟做错了什么?

I tried using a for loop and print the length of every side of a triangle, but the result is still 5.0 and printed just once.我尝试使用 for 循环并打印三角形每条边的长度,但结果仍然是 5.0 并且只打印了一次。 Now I tried to print the recursive sum at every step but no results现在我尝试在每一步打印递归和但没有结果

public static void main(String[] args) {
        int i;
        double result = 0;
        double x1 = Double.valueOf(args[1]);
        double y1 = Double.valueOf(args[2]);
        Punto p1 = new Punto(x1, y1);
        double x2 = Double.valueOf(args[3]);
        double y2 = Double.valueOf(args[4]);
        Punto p2 = new Punto(x2, y2);
        double x3 = Double.valueOf(args[5]);
        double y3 = Double.valueOf(args[6]);
        Punto p3 = new Punto(x3, y3);
        Punto[] punti = {p1, p2, p3};
        Poligono A = new Poligono(args[0], punti);
        for (i = 0; i < punti.length - 1; i++) {
            double xa = Punto.getX(punti[i++]);
            double xb = Punto.getX(punti[i]);
            double ya = Punto.getY(punti[i++]);
            double yb = Punto.getY(punti[i]);
            result = result + Math.sqrt(Math.pow(Math.abs(xa - xb), 2) + Math.pow(Math.abs(ya - yb), 2));
            System.out.println(result);
        }
    }

(Punto means point) The right answer is 12, but it always prints 5 and just once (Punto 表示点)正确答案是 12,但它总是打印 5 并且只打印一次

You should probably replace double xa = Punto.getX(punti[i++]);你应该替换double xa = Punto.getX(punti[i++]); with double xa = Punto.getX(punti[i + 1]); double xa = Punto.getX(punti[i + 1]); so that you don't modify i as it is used to iterate through the array.这样您就不会修改i ,因为它用于遍历数组。

The correct answer to your question is already there by @devgianlu! @devgianlu 已经为您的问题提供了正确答案!

However, I would like to add that, when something apparently not-reasonable happens, try to debug your code (executing step by step the lines, for example).但是,我想补充一点,当发生明显不合理的事情时,请尝试调试您的代码(例如,逐步执行这些行)。 You will discover that the machine always does what we say to do.你会发现机器总是按照我们说的去做。 Sometimes we think to declare a specific task but, in reality, we are declaring unintentionally something else.有时我们想声明一个特定的任务,但实际上,我们无意中声明了其他事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM