2012-12-19 50 views
0

我必须将摄氏温度转换为华氏温度。但是,当我以摄氏度打印温度时,我得到了错误的答案!请帮忙 ! (公式是c =(5/9)*(f -32)。当我输入1度数时,我得到c = -0.0。我不知道什么是错的:s温度转换

这里是代码

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); 
    } 
} 
+0

非常感谢你:)我很困惑哈哈:p – MadcapClover

回答

4

你正在做的整数除法,因此5/9会给你0

将其更改为浮点除法: - 。

c = ((f-32) * (5.0/9)); 

或,执行乘法第一(从分割删除括号): -

c = (f-32) * 5/9; 

由于,f加倍。分子只会是double。我认为这种方式更好。

0

您应该尝试使用double而不是int,因为这会导致精度损失。而不是使用整个公式,使用一个计算在一个时间

实施例:使用合适的铸造 双此= 5/9

的F - 双32

0

使用这种相当:

c = (int) ((f-32) * (5.0/9));// Calculates the degrees in Celcius 

,因为它涉及的部门,你不应该只使用整数得到适当的分工

0

使用此

System.out.println((5F/9F) * (f - 32F)); 
0

除非明确指定,否则Java会将所有数字视为整数。由于整数不能存储数字的小数部分,所以当执行整数除法时,其余部分将被丢弃。因此:5/9 == 0

Rohit的解决方案c = (f-32) * 5/9;可能是最干净的(尽管缺乏显式类型可能会导致一些混淆)。