我编写了两个基本函数,以便将摄氏度转换为华氏度,反之亦然。 我的问题是第一次转换是错误的,我不知道为什么它返回了错误的值。而且我也不知道为什么数字后面有一个“”。
功能如下:
function celsiusToFahrenheit (celsius) {
let fahrenheit = celsius * (9/5) + 32;
document.getElementById('fahrenheit').innerHTML = celsius + "ºC is " + celsius + "ºF";
}
function fahrenheitToCelsius (fahrenheit) {
let celsius = (fahrenheit - 32) / (9/5);
document.getElementById('celsius').innerHTML = fahrenheit + "ºF is " + celsius + "ºC";
}
celsiusToFahrenheit(25);
fahrenheitToCelsius(120);
但是当我在浏览器上看到它时,我得到的是:
25ºC is 25ºF
120ºF is 48.888888888888886ºC
最佳答案
the first conversion is wrong
将第二个摄氏度
更改为华氏
:
document.getElementById('fahrenheit').innerHTML = celsius + "ºC is " + celsius + "ºF";
I also don't know why there is a "Â" after the numbers.
您可以通过使用 HTML 实体表示度数 (°
) 来克服字符编码问题:
document.getElementById('celsius').innerHTML = fahrenheit + "°F is " + celsius + "°C";
片段:
function celsiusToFahrenheit(celsius) {
let fahrenheit = celsius * (9 / 5) + 32;
document.getElementById('fahrenheit').innerHTML = celsius + "°C is " + fahrenheit + "°F";
}
function fahrenheitToCelsius(fahrenheit) {
let celsius = (fahrenheit - 32) / (9 / 5);
document.getElementById('celsius').innerHTML = fahrenheit + "°F is " + celsius + "°C";
}
celsiusToFahrenheit(25);
fahrenheitToCelsius(120);
<div id="fahrenheit"></div>
<div id="celsius"></div>
关于javascript - 函数返回错误值并且其中一个字符是意外的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47103596/