Oaztargi
Oaztargi

Reputation: 13

Celsius to Fahrenheit conversion -- Java

Hello I'm pretty new to Java, so I'm still getting familiar with it. Right now I'm doing a lab for class and I've got it mostly figured out, but there's a section in which we are required to convert Celsius to Fahrenheit. I'm a bit stumped because we're required to keep the first conversion as an int data type.

In our lab we have test classes, and according to the test class the first conversion (the int data type) inputs -40 degrees Celsius, runs the conversion method, and should get the result of -40 degrees Fahrenheit.

This is actually a user-defined class called Conversion that I'm writing.

Here's the snippet I'm working with right now:

public static int celsiusToFahrenheit(int temp)
{
    return (temp * (9/5)) + 32;
}

public static double celsiusToFahrenheit(double temp)
{
    return (temp * (9.0/5.0)) + 32.0;
}

the second part works fine, inputting 12.5 degrees Celsius and returning 54.5 degrees Fahrenheit.

As I mentioned I'm still pretty new to Java so if there's anything else you need from me please let me know.

Question I'm asking, sorry -- Any ideas on how I can write the return statement so that it gives the correct conversion?

Edit: I've corrected it. I realized that the ints would give me a rounded value, but I wasn't sure how to get around it. I got it into my mind that I couldn't type cast here so I didn't even try to explicitly cast it back to int. All is well now:

public static int celsiusToFahrenheit(int temp)
{
    return (int) ((temp * (9.0/5.0)) + 32);
}

Upvotes: 1

Views: 2898

Answers (3)

connan
connan

Reputation: 91

Your int version fails at the (9/5) part. Since 9 and 5 are both ints, the result from the division will be an int aswell (-> 1), so it will compute temp * 1 + 32. Try using at least 1 float or double in that division, to promote the result to floating point precision.

Since I can't add comments yet, you should note that the proposed solution without casting will not yield the same answers for all inputs.

(int)(-1 * (9 / 5.0) + 32) // 30
-1 * 9 / 5  + 32 // 31

30 is closer to the actually correct result, 30.2 Even tho you are returning an int, you should generally put the part where you lose precision as late as possible to avoid rounding errors and the like.

Upvotes: 2

Tammy Nguyen
Tammy Nguyen

Reputation: 26

Here's a solution that doesn't use type casting.
9/5 in the first method is integer division, resulting in

-40 * 1 + 32 = 8

Rewrite the return expression as (temp * 9 / 5 ) + 32 (remove the parentheses around 9/5. This will force temp * 9 first and then division by 5 after.

Upvotes: 0

BratBart
BratBart

Reputation: 407

However you did not write question ;)!

public static double celsiusToFahrenheit(int temp)
{
return (temp * (9.0/5)) + 32;
}

public static double celsiusToFahrenheit(double temp)
{
return (temp * (9.0/5.0)) + 32.0;
}

Upvotes: 0

Related Questions