Loading...
Image

使用JavaScript的温度转换器

首页 / 新闻资讯 / 正文

我们需要编写一个JavaScript函数,该函数接受一个表示摄氏或华氏温度的字符串。

像这样-

"23F", "43C", "23F"

我们需要编写一个JavaScript函数,该函数接受此字符串并将温度从摄氏温度转换为华氏度,并将华氏温度转换为摄氏温度。

示例

以下是代码-

const temp1 = '37C'; const temp2 = '100F'; const tempConverter = temp => {    const degree = temp[temp.length-1];    let converted;    if(degree === "C") {       converted = (parseInt(temp) * 9 / 5 + 32).toFixed(2) + "F";    }else {       converted = ((parseInt(temp) -32) * 5 / 9).toFixed(2) + "C";    };    return converted; }; console.log(tempConverter(temp1)); console.log(tempConverter(temp2));

输出结果

以下是控制台中的输出-

98.60F 37.78C