Results 1 to 4 of 4
  1. #1
    chrismanahan is offline Member
    Join Date
    Oct 2009
    Posts
    2
    Rep Power
    0

    Default Problem with division using doubles

    Hey guys,
    I'm working on a project in my beginner Java class and the only thing that is not working is division. I feel like it might just be something really simple I can't see, but every time I divide two numbers and assign it to a double, the answer truncates itself like an int and loses all values that aren't whole numbers. Here for example, is a program that converts fahrenheit to celsius:

    Java Code:
    public class test
    {
    	public static void main(String [] args)
    	{
    		double c;
    		double boil = 212;
    		String output;
    
    		c = (boil - 32) * (5/9);
    		output = boil + " in Fahrenheit is " + c + " in Celsius.";
    		System.out.println(output);
           }
    }
    This outputs c = 0 for me because the problem is the 5/9. Instead of being .556, it truncates and is 0.


    This code below doe the same thing except instead of using (5/9), I assign the values 5 and 9 to two double vars called one and two, divide, and get the correct answer.
    Java Code:
    public class test
    {
    	public static void main(String [] args)
    	{
    		double one, two;
    		double c;
    		double boil = 212;
    		String output;
    
    	        one = 5;
    		two = 9;
    		c = (boil - 32) * (one / two);
    		output = boil + " in Fahrenheit is " + c + " in Celsius.";
    		System.out.println(output);
           }
    }
    Please help me out! I worked on this for 4 hours last night and couldn't figure out what is wrong

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

  3. #3
    chrismanahan is offline Member
    Join Date
    Oct 2009
    Posts
    2
    Rep Power
    0

    Default

    Oh my god thanks dude. You're a savior

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

Similar Threads

  1. java division and decimal error
    By heartysnowy in forum New To Java
    Replies: 5
    Last Post: 10-07-2009, 04:57 PM
  2. how to discard remainder on division?
    By RobertF in forum New To Java
    Replies: 9
    Last Post: 03-13-2009, 12:20 PM
  3. arrays strings and doubles
    By rgvbabe in forum New To Java
    Replies: 1
    Last Post: 01-13-2008, 11:26 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •