【问题标题】:Temperature Convertions温度转换
【发布时间】:2012-12-19 06:28:46
【问题描述】:

我必须将摄氏温度转换为华氏温度。但是,当我以摄氏度打印温度时,我得到了错误的答案!请帮忙 ! (公式是 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);
    }
}

【问题讨论】:

  • 非常感谢大家 :) 我很困惑哈哈 :p

标签: java temperature


【解决方案1】:

您正在进行整数除法,因此5 / 9 将给出您的0

改为浮点除法:-

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

或者,先做乘法(从除法中去掉括号):-

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

因为,f 是双倍的。分子仅为double。我认为这种方式更好。

【讨论】:

    【解决方案2】:

    改用这个:

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

    因为它涉及除法,你不应该只使用整数来获得正确的除法

    【讨论】:

      【解决方案3】:

      使用这个

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

      【讨论】:

        【解决方案4】:

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

        示例:使用适当的强制转换 双倍 = 5/9

        F - 双32

        【讨论】:

          【解决方案5】:

          除非另有明确说明,Java 将所有数字视为整数。由于整数不能存储数字的小数部分,因此在执行整数除法时,余数被丢弃。因此:5/9 == 0

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-01-17
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多