简体   繁体   中英

Java how to fill array

public static void main(String[] args) {

float numberF[]=new float[7];
displayF(numberF);

}

public static void displayF(float x[]) {

    int one = 1;
    double sum = 0;
    for (int row = 0; row < x.length; row++) {
        sum = Math.pow(one, 2);
        x[row] = (int) sum;

        System.out.printf("%.0f.%.0f ",x[row], x[row] );
        one++;
    }

}

This method gives me this output:

1.1 4.4 9.9 16.16 25.25 36.36 49.49

But I need the array to store the numbers above with a for loop. Now it only stores 1.0 4.0 9.0 etc...

Any suggestions of how to do it?

There are other more efficient ways to do it, but the easiest is just to parse what you are printing back into a float:

x[row] = Float.parseFloat(String.format("%.0f.%.0f", sum, sum));

As noted by SMA in the comments, this won't give an exact answer due to rounding errors. You can store the exact value if you change the array type to BigDecimal :

x[row] = new BigDecimal(String.format("%.0f.%.0f", sum, sum));

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