简体   繁体   中英

Loss of precision during a for loop [arrays]

double [] temperature = new double[length];    
// After this, the doubles are added to the array after being read from a file.    
for (int i : temperature) 
{
    System.out.printf("%5s" , i.toString());
}

During the for loop, I get the error "possible loss of precision required int; found: double" around the 'temperature' part of the loop. How can I create a for loop to print the values of the doubles in this string?

Change:

for(int i : temperature) 

to

for(double i : temperature) 

Note that temperature is an array of double s and not int s.

How does your code compile? Are you sure i.toString() gives you no errors? It's enough to print i .

你应该使用

for (double i : temperature)

Well, the problem is that your array is full of doubles and you're treating them as ints. Say something like for(double i:temperature) instead.

I would suggest keeping the temperatures as a double throughout, rather than converting them to int . Also, instead of using toString() to convert, you could specify in the format string how to format the double . For example, if you want the double values printed to two decimal places, you could write

for (double eachTemperature : temperature) {
    System.out.format("%.2f%n", eachTemperature);
}

More information about the different format strings you can use is at http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html

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