Results 1 to 3 of 3
Thread: Method won't return value
- 03-26-2010, 10:32 AM #1
Method won't return value
Hi All,
Yet another Java newbie here learning the basics. :D
I can't figure out why this method 'fahrenheitToCelsius' won't return a double value. Can someone please help me?
Java Code:public class TempConversion508 { public static void main(String[] args) { double test = fahrenheitToCelsius(120.0); System.out.println(test); } public static double fahrenheitToCelsius(double fahrenheit) { return (120.0 - 32.0) * (5 / 9); } }
Output is: 0.0
Thanks!
Ash
- 03-26-2010, 10:48 AM #2
Yup. 5 / 9 is integer division, which is rounded down.
Either use at least one double value 5.0 / 9 or 5 / 9.0 or cast one of the ints to doubleJava Code:((double) 5) / 9
db
- 03-26-2010, 10:49 AM #3
the result is ok. if you devide two integer like you do ( 5 / 9 ) the result is an integer resp. 0, so your term become 0. to get a right result a quick solution is changing 5 or 9 to double 5.0 or 9.0 so that your term is (120.0 - 32.0) * (5 / 9.0). the result will now be automatically converted to an double so that the result of your term will be a double. an other solution is a explicit cast to double, like db explaine above.
the automatic type promotion is a very important and basic concept in java. so i suggest to spend enough time to learn it.Last edited by j2me64; 03-26-2010 at 10:52 AM.
Similar Threads
-
Return an object to use in another method
By TidusSolan in forum New To JavaReplies: 3Last Post: 03-19-2009, 08:00 PM -
method that return 2 arguments
By itaipee in forum New To JavaReplies: 19Last Post: 01-12-2009, 05:36 PM -
return a null method
By valoyivd in forum New To JavaReplies: 2Last Post: 04-21-2008, 11:19 PM -
Return question in a method.
By MetalGear in forum New To JavaReplies: 1Last Post: 01-13-2008, 04:45 AM -
Return value of method
By cachi in forum New To JavaReplies: 1Last Post: 08-01-2007, 08:23 AM
Bookmarks