基本的java温度转换器

时间:2013-06-10 01:39:50

标签: java converter temperature

所以我正在尝试编写一个程序来将C度转换为F,反之亦然。每次我运行程序时,我都会遇到错误,我无法解释。例如,它将100 C转换为132 F.它将212 F转换为0 C.我的转换公式是正确的。谁能给我一些线索?我尝试在主要的课堂外宣布花车,但没有帮助。

import java.util.Scanner;
public class TempConverter{
public static void main(String [] args)
{
    float f, c;
    f = c = 0;
    int a;
    Scanner scan = new Scanner (System.in);
    System.out.println("Press 1 for C->F or 2 for F->C");
    a = scan.nextInt();
    if (a == 1) 
        convertCtoFAndPrint();
    else
        convertFtoCAndPrint();
}

public static void convertFtoCAndPrint()
{
    f = c = 0;
    Scanner scan = new Scanner (System.in);
    System.out.println("Please enter degrees F");
    f = scan.nextFloat();
    c = (5/9)*(f-32);
    System.out.println(f + " degrees F is " + c + " degrees C.");
}

public static void convertCtoFAndPrint()
{
    Scanner scan = new Scanner (System.in);
    System.out.println("Please enter degrees C");
    c = scan.nextFloat();
    f = c*(9/5)+32;
    System.out.println(c + " degrees C is " + f + " degrees F.");
}

}

1 个答案:

答案 0 :(得分:3)

你写道:

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

cfloat

问题是5 / 9整数除法,其结果始终为0.

类似地:

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

此处9 / 5始终为1. c将投放到int

您需要撰写5.09.0