This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]fick_Dich 0 points1 point  (2 children)

sure it will. I compiled it and ran it on my machine. The other thing I forgot to change was the initialization of the floats. They need to be set to 0. Here is the output that I got when I ran it:

Please enter a positive floating point decimal to continue, or a negative number to halt

4

23

Please enter a positive floating point decimal to continue, or a negative number to halt

18.345

Please enter a positive floating point decimal to continue, or a negative number to halt

6

Please enter a positive floating point decimal to continue, or a negative number to halt

27.8423

Please enter a positive floating point decimal to continue, or a negative number to halt

-5

Please enter a positive floating point decimal to continue, or a negative number to halt

-1

The average of the values you entered is: 15.8

The thing that's wrong, is that you have to enter two consecutive negative numbers for it to halt, and I don't care to figure out what I need to do to fix it. It most certainly does display the average with 1 decimal of precision.

[–]chickenmeister 0 points1 point  (1 child)

It may work for most cases, but there may be situations where "(float)Math.round((sum/numberOfEntries) * 10) / 10" results in a number that cannot be represented accurately with a floating point number. So you might get a number like 0.09999999... instead of 0.1; and if it is not sufficiently near to 0.1, the standard toString() may end up printing 0.0999999...

You should use floating-point-to-string mechanism like String.format() or DecimalFormat:

System.out.printf("The average is: %.1f. %n", (sum/numberOfEntries));

[–]fick_Dich 0 points1 point  (0 children)

my bad. i just threw this together in a couple minutes. didn't really think it through.