processing float in java
in java, i have an array of floats, some of them are negative numbers, like :
3.04, 9.02, -4.2, -3.21, 0.02, -0.34
I only want to get the float numbers higher than 2,开发者_JS百科 so I used :
if(number > 2.0 ) print.. etc
but what i get is not only the numbers >2, also the negative numbers :
3.04, 9.02, -4.2, -3.21
what could be the problem ?
It's hard to tell what the problem is without seeing code. Writing the obvious code from your description, it works fine:
public class Test {
public static void main(String[] args) {
float[] floats = { 3.04f, 9.02f, -4.2f, -3.21f, 0.02f, -0.34f };
for (float number : floats) {
if (number > 2.0) {
System.out.println(number);
}
}
}
}
Compare your code with mine - if you still can't get yours to work, please edit your question with your code.
Based on comments and question, assuming we have a file named numbers.txt
with content:
3.04 9.02 -4.2 -3.21 0.02 -0.34
this code should do the trick (I ommited exception handling for readibility):
float[] floats = new float[100]; // adjust as needed
String fileName = "numbers.txt";
File f = new File(fileName);
BufferedReader br = new BufferedReader(new FileReader(f));
String line = "";
int i = 0;
while( (line = br.readLine()) != null) {
if(line == null || line.isEmpty()) continue; // just in case there are empty lines in file
floats[i] = Float.parseFloat(line);
i++;
}
br.close();
for (float number : floats) {
if (number > 2.0) {
System.out.println(number);
}
}
Output:
3.04 9.02
This is too long for a comment but it should be pointed out that if you write:
if (number > 2.0)
then you probably shouldn't be working with floating-point numbers because you don't understand yet how they work.
There's a good Wikipedia page on floating point numbers:
http://en.wikipedia.org/wiki/Floating_point
Then I suggest reading the 80 pages long "What every computer scientist should know about floating-point numbers".
Basically: due to the limited precision of floating point numbers, comparison should typically always be done using an epsilon.
Things like: if (number > 2.0) are a big no-no.
精彩评论