Matt Gerrans
Posts: 1153
Nickname: matt
Registered: Feb, 2002
|
|
Re: New to Java: How Do You Average Numbers?
|
Posted: Sep 3, 2002 12:37 PM
|
|
Here's one that works a little better:public class AverageNumbers
{
public static void main(String [] args)
{
int firstNo = 80;
int secondNo = 85;
int thirdNo = 90;
System.out.println( "80 and 85 and 90: " + (80 + 85 + 90)/3 );
}
}
The major differences are: - Uses square braces to indicate args is an array. - Semicolons after each statement (int declarations). - Changed "print.out" to "System.out". - Removed extra right-paren in the print statement. - Most importantly, used the [ java ] tags to get nice formatting in the forum message.
It still has problems. Averaging ints is a dicey proposition, especially if there is a small number of them or if they have very large values. Values are hard-coded, particularly in the print statement. Probably, you would want to have a method that takes an array of ints and returns their average in a float, or maybe an int, if you don't care about the truncation (for instance, when positioning windows on a screen, you might do something like that, since you don't care wether it is off by a pixel).
|
|