1
public static double[] creeVec(double x, double y, double z){

    //cree et retourne un tableau
    double[] tab = new double[3];
    tab[0]=x;
    tab[1]=y;
    tab[2]=z;
    return tab;
}

public static double longueur(double[] tab){

    //calcule la longueur
    tab = new double[3];
    double carre = ((tab[0]*tab[0])+(tab[1]*tab[1])+(tab[2]*tab[2]));
    return Math.sqrt(carre);
}

And then when I called them to get my result of Math.sqrt() I get 0

    double[] v1 = Vec3DTab.creeVec(10, 20, 30);
    double[] v2 = Vec3DTab.creeVec(4, 5, 6);

    //affiche la longueur de v1
    double LongueurV1 = Vec3DTab.longueur(v1);
    System.out.println(LongueurV1);
John Hascall
  • 9,176
  • 6
  • 48
  • 72
Atala
  • 1
  • 6

3 Answers3

4

The code tab = new double[3]; in longueur(double[] tab) method creates a new double array object and initializes with default value of 0.

Hence it returns 0.

Please remove this line and you will get proper value.

1

Doing:

double[] v1 = Vec3DTab.creeVec(10, 20, 30);
double[] v2 = Vec3DTab.creeVec(4, 5, 6);

is bad form, do:

double[] v1 = Vec3DTab.creeVec(10.0, 20.0, 30.0);
double[] v2 = Vec3DTab.creeVec(4.0, 5.0, 6.0);

but it seems like you are going to a lot of rigmarole to get

double[] v1 = {10.0, 20.0, 30.0};
double[] v2 = {4.0, 5.0, 6.0};

but your real problem is here:

public static double longueur(double[] tab){

//calcule la longueur
tab = new double[3];     // <== this is hiding the tab above which has the values
                         // this just has zeros.
John Hascall
  • 9,176
  • 6
  • 48
  • 72
  • Disagree on it being bad form to omit the `.0`, though totally agree on the apparent roundabout way here of defining a simple 3-array. I find `{10, 20, 30}` easier on the eyes. Or `{10d, 20d, 30d}` if you really want to be explicit about types. – Riaz Jan 29 '16 at 04:27
  • I see beginners do stuff like `double ftoc = 9/5;` a lot; so IMO it's best to get people in the practice of always making doubles look like doubles. I know experienced programmer love shortcuts (like how C allows `if (intvar)` but Java makes you say `if (intvar != 0)`, but they are to me an easily avoided common source of errors. – John Hascall Jan 29 '16 at 13:10
1

Reason: you are clearing the value you passed in to the method., therefore all the array elements are set to zero.

//calcule la longueur
 tab = new double[3];     //  <-- here are you clearing the vector

Solution: Remove the new initialization of the tab array

public static double longueur(double[] tab){
    //calcule la longueur
    double carre = ((tab[0]*tab[0])+(tab[1]*tab[1])+(tab[2]*tab[2]));
    return Math.sqrt(carre);
}
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97