LoginSignup
0
0

More than 3 years have passed since last update.

JavaScriptで円周率の有効桁数をユーザーに指定してもらう方法

Last updated at Posted at 2020-10-11

<main>
<div class="container">
<section>
    <p>これが有効桁数<span id="digit"></span>円周率<span id='pi'></span>です</p>

</section>
</div><!-- /.container -->
</main>
<footer>
<div class="container">
<p>JavaScript Samples</p>
</div><!-- /.container -->
</footer>
<script>
'use strict';
const digits=parseInt(window.prompt('有効桁数を数字で入力してね'));
const DIGIT=digits-1;
 function point(num,digits){
     const mover =10**digits;
     return Math.floor(num*mover)/mover;

 }
document.getElementById('digit').textContent=digits;
document.getElementById('pi').textContent=point(Math.PI,DIGIT)

</script>
</body>
</html>

参考文献:JavaScript超入門書P174

(説明)
まず、window.prompt('')でユーザーに有効桁数を入力してもらう。
そのデータが文字列(string)なので、parseInt()メソッドで数値、整数(integer)に変換する。
その値を、定数digitsに代入。
円周率(Math.PI)の指定した小数点以下を切り捨てる関数を作る。function point(num,digits)
しかし、3.14159265358979を10*digitsした後に小数点以下を切り捨てても、もともと小数点の前(一の桁)にある3も有効桁数に入るので、このままだとユーザーが入力した桁数より1桁多くなる
(ex:ユーザーの有効桁数「3」
3.141592x10
3=3141.592
この数字の小数点以下を切り捨てると3141
これをまた元の数字に戻すと
3141/10
*3=3.141
つまり有効数字4桁になってしまう。)
よって、私は
const DIGIT=digits-1;
document.getElementById('pi').textContent=point(Math.PI,DIGIT)
この二つのコードを工夫して、出力をユーザーが求める有効桁数にした。
関数を呼び出すときの引数にpoint(Math.PI,DIGIT)をして、円周率とユーザーが入力した有効桁数−1で帳尻を合わせた。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0