编码蝙蝠练习TempConvert

时间:2014-02-15 05:21:11

标签: java

您想要创建一种方法,将温度从华氏温度转换为摄氏温度,反之亦然。你会得到两件事。首先,将当前温度测量值作为小数。第二,电流测量所依据的规模。如果温度以华氏度给出,则第二个变量将为'f'。使用以下等式,将其转换为摄氏度并返回值。 C =(F-32)的(5/9)。如果温度以摄氏度给出,则第二个变量将为'c'。使用以下等式将其转换为华氏温度并返回该值。 F =(C (9/5))+ 32。

TempConvert(100.0,'c')→212.0

TempConvert(0.0,'c')→32.0

TempConvert(22.0,'c')→71.6

我无法弄明白......我需要帮助!!!

public double TempConvert(double temp,char scale) {
    double cent=(faren-32)*(5/9);
    double faren=(cent*(9/5))+32;

    if (temp==faren)
        scale = 'f';
    else if (temp==cent)
        scale = 'c';
}

任何想法!!请帮忙!!

1 个答案:

答案 0 :(得分:1)

这是处理它的快速方法。

public double TempConvert(double temp,char scale) {
    if (scale=='c') // the current temp is in Celsius
        return ((temp*9)/5)+32; // fixed for order of operations
    if (scale=='f') // the current temp is in Fahrenheit
        return ((temp-32)*5)/9; // fixed for order of operations
    return -1; // incorrect char selected
}

编辑 - 更简单的方法。

由于你使用的是双打,你的整数需要加倍。 Java将5/9视为整数5除以整数9.将它们分别更改为5.0和9.0可以修复。

public double TempConvert(double temp,char scale) {
    if (scale=='c') 
        return (9.0/5.0)*temp+32;
    if (scale=='f')
        return (temp-32)*(5.0/9.0);
    return -1;
}