我如何在 javascript 中使用 Math.sin() 来获得正确答案?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22745229/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 23:42:22  来源:igfitidea点击:

How do i use Math.sin() in javascript to get correct answer?

javascriptmath

提问by JaSamSale

When I use Math.sin(90) for calculating Sine of 90 degrees in javascript it returns 0.8939966636005565, but sin(90) is 1. Is there a way to fix that? I need accurate values for any angle.

当我使用 Math.sin(90) 在 javascript 中计算 90 度的正弦时,它返回 0.8939966636005565,但 sin(90) 是 1。有没有办法解决这个问题?我需要任何角度的准确值。

<!DOCTYPE html>
<html>
<body>
    <p id="demo">Click the button calculate value of 90 degrees.</p>
    <button onclick="myFunction()">Try it</button>
<script>
function myFunction(){
    document.getElementById("demo").innerHTML=Math.sin(90);
}
</script>

回答by thefourtheye

Math.sinexpects the input to be in radian, but you are expecting the result of 90 degree. Convert it to radian, like this

Math.sin期望输入为弧度,但您期望结果为 90 度。把它转换成弧度,像这样

console.log(Math.sin(90 * Math.PI / 180.0));
# 1

As per the wikipedia's Radian to Degree conversion formula,

根据维基百科的弧度到度数转换公式

Angle in Radian = Angle in Degree * Math.PI / 180

回答by sjf

The sin function in Javascript takes radians, not degrees. You need to convert 90 to radians to get the correct answer:

Javascript 中的 sin 函数采用弧度,而不是度数。您需要将 90 转换为弧度以获得正确答案:

Math.sin(90 * (Math.PI / 180))