2014-02-15 97 views
0

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

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

你为什么要在体内设置scale?我认为'scale'是决定'temp'是否是F或C值的输入。 – jia103

+0

我是一个初学者,有点从网络上获得灵感。我不知道下一步该怎么做。任何帮助都会有所帮助。 – sciontoygirl

回答

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; 
}