Results 1 to 4 of 4
- 10-10-2009, 07:31 PM #1
Member
- Join Date
- Oct 2009
- Posts
- 2
- Rep Power
- 0
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:
This outputs c = 0 for me because the problem is the 5/9. Instead of being .556, it truncates and is 0.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 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.
Please help me out! I worked on this for 4 hours last night and couldn't figure out what is wrongJava 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); } }
-
make it 5.0/9.0 so that you don't inadvertently do int division here.
- 10-10-2009, 08:48 PM #3
Member
- Join Date
- Oct 2009
- Posts
- 2
- Rep Power
- 0
Oh my god thanks dude. You're a savior
-
Similar Threads
-
java division and decimal error
By heartysnowy in forum New To JavaReplies: 5Last Post: 10-07-2009, 04:57 PM -
how to discard remainder on division?
By RobertF in forum New To JavaReplies: 9Last Post: 03-13-2009, 12:20 PM -
arrays strings and doubles
By rgvbabe in forum New To JavaReplies: 1Last Post: 01-13-2008, 11:26 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks