构造函数未初始化正确的值

时间:2019-03-10 06:58:08

标签: java

我是Java的新手,在下面的代码中,我有2个类,即Start.java和ecuație.java。 ecuatie.java计算平方二次方的平方英尺,但是由于某种原因,构造函数无法正确初始化值。你能告诉我为什么会这样吗?

package com.ecuatie;

import com.ecuatie.ecuatie;

public class Start {

  public static void main(String[] args) {
      ecuatie exemplu = new ecuatie(1.0d, 0.0d, -4.0d);

      System.out.println(exemplu.delta() + '\n');

      System.out.println(exemplu.X1() + '\n');
      System.out.println(exemplu.X2() + '\n');
  }
}


package com.ecuatie;

import java.lang.Math;

public class ecuatie {
       private double a = 0, b = 0, c = 0;

       ecuatie(double a, double b, double c) {
         this.a = a; this.b = b; this.c = c;
       }

       public double delta() {
         return (b * b) - (4 * a * c);
       }

       public double X1() {
         return (-b + Math.sqrt(delta())) / (2 * a);
       }

       public double X2() {
         return (-b - Math.sqrt(delta())) / (2 * a);
       }
}

1 个答案:

答案 0 :(得分:2)

您得到的是因为它添加了char的ASCII值。

'\ n'的ASCII值为10。所以就像您+ exemplu.delta()为10一样。 同样,在使用println()时也不需要添加回车。

所以您只需要这样编写代码即可。

  public static void main(String[] args) {
  ecuatie exemplu = new ecuatie(1.0d, 0.0d, -4.0d);

     System.out.println(exemplu.delta() );

     System.out.println(exemplu.X1() );
     System.out.println(exemplu.X2() );
  }