首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >温度转换

温度转换
EN

Stack Overflow用户
提问于 2012-12-19 14:28:47
回答 5查看 2.1K关注 0票数 0

我得把摄氏温度换算成华氏温度。然而,当我以摄氏度为单位打印温度时,我得到了错误的答案!请帮帮我!(公式是c= (5/9) * (f -32)。当我输入华氏1度时,我得到c= -0.0。我不知道出了什么问题:s

以下是代码

代码语言:javascript
复制
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);
    }
}
EN

回答 5

Stack Overflow用户

发布于 2012-12-19 14:32:53

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

将其更改为浮点除法:

代码语言:javascript
复制
c = ((f-32) * (5.0/9));

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

代码语言:javascript
复制
c = (f-32) * 5 / 9;

因为,f是双精度的。分子将仅为double。我觉得这种方式更好。

票数 4
EN

Stack Overflow用户

发布于 2012-12-19 14:34:24

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

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

F-双32

票数 0
EN

Stack Overflow用户

发布于 2012-12-19 14:35:31

而不是使用这个:

代码语言:javascript
复制
c = (int) ((f-32) * (5.0/9));// Calculates the degrees in Celcius 

因为它涉及除法,所以您不应该只使用it来获得正确的除法。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13946711

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档