Results 1 to 2 of 2
Thread: Basic java help =)
- 06-29-2010, 07:28 PM #1
Member
- Join Date
- Jun 2010
- Posts
- 15
- Rep Power
- 0
Basic java help =)
Hi,
I'm brand new to Java. I have taken a couple classes of c++ before but just started this Java one.
I have an assignment to create a program that generates three random numbers and then calculates the average for them.
I thought I had it finished pretty quick and easy, until I realized its not averaging quite right. If the average is 13.66666, it'll just output 13.0. if its 7.43 it'll output 7.0. Always .0.
How do I go about getting it to output the correct decimal, and how do I set it to for example, two decimal slots?
This is what I have for my program so far.
Edit: I think I just realized its not the output that is the issue, but that its probably doing integer math and not storing the decimal into average at all. Trying to figure it out now, I probably can since I know what I'm looking for now.Java Code:package chapter3ec; import java.util.Random; public class RandomNumbers { public static void main( String [ ] args ) { Random random = new Random( ); // Generate three random numbers between 0 and 50 int start = 0, end = 50; System.out.println( "Generating three numbers between " + start + " and " + end + "..."); int number = random.nextInt( end - start + 1 ) + start; int number2 = random.nextInt( end - start + 1 ) + start; int number3 = random.nextInt( end - start + 1 ) + start; //Outputs each of the three numbers generated. System.out.println( "First number: " + number); System.out.println( "Second number: " + number2); System.out.println( "Third number: " + number3); //Calculates the average of the three numbers float average = (number + number2 + number3) / 3; //Outputs the average of the three numbers System.out.println( "The average of the three numbers is: " + average); } }
Edit2: I figured it out.
I changed
float average = (number + number2 + number3) / 3;
to:
float average = (float) ((number + number2 + number3) / 3.0) ;
Nevermind guys =). Thanks anyways though. I may be back as I have a couple other assignments to do today as well.Last edited by Xycose; 06-29-2010 at 07:49 PM.
- 06-30-2010, 02:20 AM #2
Senior Member
- Join Date
- Feb 2010
- Location
- Waterford, Ireland
- Posts
- 748
- Rep Power
- 4
Similar Threads
-
Basic Java help, AIM?
By jkswebsite in forum New To JavaReplies: 4Last Post: 07-11-2012, 06:17 PM -
Basic java
By santa in forum New To JavaReplies: 5Last Post: 11-16-2009, 10:16 AM -
basic java
By vijay24805 in forum New To JavaReplies: 25Last Post: 04-14-2009, 02:46 AM -
basic java help
By adred in forum New To JavaReplies: 0Last Post: 03-08-2008, 12:36 PM -
help with basic java code
By elizabeth in forum New To JavaReplies: 1Last Post: 08-07-2007, 06:47 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks