[英]Float to String Conversion - JS
So I am currently working on that function 所以我目前正在从事该职能
const countSixes = n => {
if (n === 0) return 0;
else if (n === 1) return 1;
else n = (countSixes(n-1) + countSixes(n-2)) / 2;
return n;
}
And so my question is how to convert the final floating-point value into a string? 所以我的问题是如何将最终的浮点值转换为字符串?
Every time after calling the function and trying to convert the float number it returns NaN 每次调用函数并尝试转换浮点数后,每次返回NaN
Hope to get the answer 希望得到答案
Thank you! 谢谢!
The first option works for me 第一个选择对我有用
<script> const countSixes = n => { if (n === 0) return 0; else if (n === 1) return 1; else n = (countSixes(n-1) + countSixes(n-2)) / 2; return n; } alert(countSixes(12) + "") </script>
The problem is really interesting. 这个问题真的很有趣。 Its
return
NaN
because when you return n
as String
, as the function
is called recursively so it cannot perform arithmetic operations in next level. 它
return
NaN
因为当您将n
作为String
返回时,因为该function
是递归调用的,所以它不能在下一级执行算术运算。
It will never end for certain numbers like 55
对于某些数字,例如
55
,它将永远不会结束
function countSixes(n,firstTime=true){
if (n === 0) return 0;
else if (n === 1) return 1;
else n = (countSixes(n-1,false) + countSixes(n-2,false)) / 2;
if(firstTime) return n.toFixed(10); // return string
else return parseFloat(n.toFixed(10)); // return float
}
You could convert the final value to a string with the wanted decimals. 您可以将最终值转换为带有所需小数的字符串。
const countSixes = n => { if (n === 0) return 0; if (n === 1) return 1; return (countSixes(n - 1) + countSixes(n - 2)) / 2; } console.log(countSixes(30).toFixed(15));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.