问题
I have to convert a temperature in degrees Celsius to Fahrenheit. However when I print the temperature in Celsius I get the wrong answer ! Please help ! (The formula is c = (5/9) * (f -32). When I type in 1 for degrees farenheit I get c = -0.0. I have no idea what is wrong :s
Here is the code
import java.io.*; // import/output class
public class FtoC { // Calculates the temperature in Celcius
public static void main (String[]args) //The main class
{
InputStreamReader isr = new InputStreamReader(System.in); // Gets user input
BufferedReader br = new BufferedReader(isr); // manipulates user input
String input = ""; // Holds the user input
double f = 0; // Holds the degrees in Fahrenheit
double c = 0; // Holds the degrees in Celcius
System.out.println("This program will convert the temperature from degrees Celcius to Fahrenheit.");
System.out.println("Please enter the temperature in Fahrenheit: ");
try {
input = br.readLine(); // Gets the users input
f = Double.parseDouble(input); // Converts input to a number
}
catch (IOException ex)
{
ex.printStackTrace();
}
c = ((f-32) * (5/9));// Calculates the degrees in Celcius
System.out.println(c);
}
}
回答1:
You are doing integer division, and hence 5 / 9
will give your 0
.
Change it to floating point division: -
c = ((f-32) * (5.0/9));
or, do the multiplication first (Remove the brackets from division): -
c = (f-32) * 5 / 9;
Since, f
is double. Numerator will be double
only. I think this way is better.
回答2:
use this rather:
c = (int) ((f-32) * (5.0/9));// Calculates the degrees in Celcius
as it involves division and you should not use only ints to get proper division
回答3:
Use this
System.out.println((5F / 9F) * (f - 32F));
回答4:
You should try using double instead of int as this would lead to loss of precision. Instead of using the whole formula, use one calculation at one time
Example: Use appropriate casting Double this = 5/9
F - Double 32
回答5:
Unless explicitly specified otherwise, Java treats all numbers as integers. Since integers cannot store fractional parts of numbers, when integer division is performed, the remainder is discarded. Therefore: 5/9 == 0
Rohit's solution c = (f-32) * 5 / 9;
is probably the cleanest (though the lack of explicit types may cause a bit of confusion).
来源:https://stackoverflow.com/questions/13946711/temperature-convertions