如何解决集成以摄氏度为单位转换开尔文的功能的问题
我在集成以摄氏度转换开尔文的功能时遇到问题,有人可以帮忙吗?我对这个世界还很陌生,请客气点! :)
我该怎么做才能将其转换为摄氏度?
let key = ...........
let requestCity = async (city) => {
let url = 'https://api.openweathermap.org/data/2.5/weather'
let query = '?q=' + city + '&appid=' + key;
let response = await fetch(url + query);
let data = await response.json();
return data;
}
let searchForm = document.querySelector('.search-location');
let cityValue = document.querySelector('.search-location input');
let cityName = document.querySelector('.city-name p');
let condition = document.querySelector('.condition');
let temp = document.querySelector('.temp')
let high = document.querySelector('.high')
let low = document.querySelector('.low')
let hum = document.querySelector('.hum')
let feel = document.querySelector('.feel')
// let celsius = (kelvin) => {
// celsius = math.round(kelvin - 273.15);
// return celsius
// }
updateWeather = (city) => {
cityName.textContent = city.name;
condition.innerHTML = city.weather[0].description;
temp.innerHTML = city.main.temp + '°K';
high.innerHTML = city.main.temp_max + '°K'
low.innerHTML = city.main.temp_min + '°K'
hum.innerHTML = city.main.humidity + '%'
feel.innerHTML = city.main.feels_like + '°K'
}
searchForm.addEventListener('submit',(event) => {
event.preventDefault();
let citySearched = cityValue.value;
console.log(citySearched);
searchForm.reset();
requestCity(citySearched)
.then((data) => { updateWeather(data) })
.catch((error) => { console.log(error) })
})
解决方法
有一个公式可以将开尔文转换为摄氏度(基本上只需从开尔文度数中减去 273.15 即可得到对应的摄氏度)。
这是我写的一小段代码,所以你可以理解:
function toCelsius(kelvin) {
if(Number.isFinite(kelvin)) { // Checking if kelvin is a number.
const KELVIN_CELSIUS_DIFF = 273.15; // maybe unnecessary here,but it is good practice to avoid magic numbers.
let celsius = kelvin - KELVIN_CELSIUS_DIFF;
return celsius; // could also be just return kelvin - KELVIN_CELSIUS_DIFF;
} else {
// kelvin is not a number,should be handled.
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。