简体   繁体   中英

How can I make a for-loop with array of doubles?

I'm trying to make a for-loop with an array of doubles, but it just doesn't work.

Here is the code:

double[] myDoubleArray = new double[10];
double piValue = 3.141592;

for (double i = 0; i < 10; piValue+) {
    myDoubleArray[i] += i;
}

System.out.println(myDoubleArray[2]);
System.out.println(myDoubleArray[5]);

Is this what you are trying to do?

for (int i=0; i < 10; ++i) {
    myDoubleArray[i] = Math.PI + i;
}

This populates your array of double values, starting with Pi, and incrementing by one for each of ten elements.

Actually for array indexing use int. You can follow below code

    double[] myDoubleArray = new  double[10]; 
    double piValue = 3.141592; 
    for (int i = 0; i < 10; i++) { 
          myDoubleArray[i] = piValue + i; 
    }
 System.out.println(myDoubleArray[2]);

 System.out.println(myDoubleArray[5]);

Even if your array if a double array, the indexes that correspond to each position are still int primitives.

double[] doubleArray = {2.45, 4.45};

for(int i = 0; i < doubleArray.length; i++) {
     System.out.println(doubleArray[i]); //Doing something with the double value
}


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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