2013-10-11 8 views

答えて

6

dc manualは言う:

ほとんどの算術演算は、あなたがkコマンドで設定できる「精度値」、の影響を受けています。デフォルトの精度値は0です。

/ 2つの値をポップし、最初の値からポップした2番目の値をポップし、結果をプッシュします。端数の桁数は、精度値で指定します。

だから、あなたはそれがデフォルトである、精度が0であることがわかっている場合0k1/、または単に1/を使用して(ゼロへの丸め)を切り捨てることができます。例:

$ dc -e '12.9 1/ p' 
12 
$ dc -e '_12.9 1/ p' 
-12 

その他の種類の丸めはより困難です。最も近い整数にラウンドするには、例えば、[_1*]sad.5r0>a+0k1/を使用することができます。

$ dc -e '12.9 [_1*]sad.5r0>a+0k1/ p' 
13 
$ dc -e '_12.9 [_1*]sad.5r0>a+0k1/ p' 
-13 

簡単に説明:

  1. [_1*]sa店コマンド_1*(-1で乗算)レジスタaインチ
  2. dは、スタックの一番上の値(丸めたい値、v)を複製します。
  3. .5r 0.5を押圧した後、上位2つの値を交換するので、スタックは今V 0.5 Vあります。
  4. 0>aレジスタにコマンドを実行aVが負である場合には、である) V > 0の場合。 V場合スタックは、Vが正であれば、今0.5 Vある、又は-0.5 V負です。
  5. +は、上位2つの値を加算し、V Vが正の場合 + 0.5、又はVプッシュ - Vが負の場合0.5。
  6. 0k1/上記のようにトランケートします。

丸めする数値が負でないことがわかっている場合は、.5+0k1/を使用することができます。また、精度が0であることが分かっている場合は、.5+1/を使用できます。

を切り捨て、[dX[1-]sa0<a]sad0>a0k1/を使用してください。

は、[dX[1+]sa0<a]sad0<a0k1/を使用してください。

これらの提案はすべてレジスタaを使用しているため、実際のプログラムで調整する必要があります。 [_1*]sa[d1r0>a+]sbd0k1/2%0!=b1/

1

ガレスの答えのビル、バンカーの丸め(最寄りさえ整数にすなわちラウンド)については、以下を使用します。

メモこれは追加のレジスタbを使用します。

ビット密です

、それでは、それを打破してみましょう:

[_1*]sa   #1- Assign a macro "$input *= -1" to register 'a' 
[d1r0>a+]sb  #2- Assign a macro "if($input<0){$input -= 1} else{$input += 1}" 
       #  to register 'b' 
d    #3- Duplicate the input value; the duplicate will be used 
       #  to decide if the input is odd or even. 
0k    #4- Set precision to 0; this makes the 1/ operation truncate 
       #  all digits to the right of the decimal point. 
1/    #5- Truncate those decimal places on our duplicate input. 
2%    #6- Modulo 2; if we get 0, it was even, otherwise it's odd. 
       #  Note this consumes the duplicate from line #3. 
0!=b   #7- If it was odd, run the macro in register 'b'. This adds +/-1 
       #  to the input, respectively if it's positive or negative. 
1/    #8- Truncate decimal places; if the input was odd we're now 
       #  at floor($input+1) for positive or floor($input-1) 
       #  for negative; if it was even we're at floor($input). 
関連する問題