Reputation: 27
I have a Fahrenheit class thats supposed to take a number from the main class and convert it into celsius. Everything works but the conversion part. I made a method that I call so that the number can be converted, but whenever the program runs it gives me either -0.0 or 0.0 (no matter what the number is) I know that the negative part is correct but i just need it to show the actual converted number.
It has been an entire year since I've done any sort of java programming and I'm still a beginner.I've looked up the java docs to get a refresher and wrote simple simple programs to get back in the game but im lost with this one. please any input would be helpful
heres the main class
public class test {
public static void main (String[] args) {
double t = 100;
Fahrenheit temp = new Fahrenheit(t);
temp.convert();
}
}
and the fahrenheit class
public class Fahrenheit{
private double tempF = 0;
public Fahrenheit (double inputTemp){
tempF = inputTemp;
}
public double convert () {
double c = 5/9*(tempF-32);
System.out.println(c );
return c;
}
}
Upvotes: 2
Views: 86
Reputation: 364928
double c = 5/9*(tempF-32);
In the above line, you are performing integer division 5 / 9, whose result is 0.
You can also use:
double c = (double)5/9*(tempF-32);
or
double c = 5.0 / 9 * (tempF-32);
Upvotes: 0
Reputation: 213391
double c = 5/9*(tempF-32);
In the above line, you are performing integer division - 5 / 9
, whose result is 0
. Hence you got 0.0
.
You can either change one of the numerator
or denominator
to a double value
: -
double c = 5.0 / 9 * (tempF-32);
or, just do the multiplication first: -
double c = 5 * (tempF-32) / 9 ;
Upvotes: 4