Share via


ユーザー定義の JScript 関数

JScript には多数の組み込み関数が用意されていますが、独自の関数も作成できます。 関数の定義は、1 つの関数ステートメントと、JScript ステートメントのブロックで構成されます。

独自の関数の定義

次の例の checkTriplet 関数は、三角形の 3 つの辺の長さを引数として受け取ります。 指定した数値がピタゴラスの三平方の定理 (直角三角形の斜辺の長さの 2 乗は、他の 2 つの辺の長さの 2 乗の和に等しい) を満たしているかどうかを調べることにより、その三角形が直角三角形かどうかを評価します。 checkTriplet 関数は、直角三角形かどうかを評価するときに、他の 2 つの関数のいずれかを呼び出します。

浮動小数点数バージョンの評価では、評価変数として非常に小さい数値 (epsilon) を使用している点に注目してください。 浮動小数点数の計算では、丸め誤差によって正しい結果が得られない場合があります。したがって、指定された 3 つの数値がすべて整数でない限り、ピタゴラスの三平方の定理を満たしているかどうかを直接調べることは、実際的ではありません。 ただし、直接比較した方がより正確に直角三角形であることを確認できるため、この例のコードでは、まず直接比較することが適切かどうかを調べ、適切である場合は直接比較する方法を使用しています。

3 つの関数を定義するときに、型の注釈は使用されていません。 このアプリケーションでは、checkTriplet 関数で整数と浮動小数点数の両方のデータ型を受け取るようにした方が便利です。

const epsilon = 0.00000000001; // Some very small number to test against.

// Type annotate the function parameters and return type.
function integerCheck(a : int, b : int, c : int) : boolean {
   // The test function for integers.
   // Return true if a Pythagorean triplet.
   return ( ((a*a) + (b*b)) == (c*c) );
} // End of the integer checking function.

function floatCheck(a : double, b : double, c : double) : boolean {
   // The test function for floating-point numbers.
   // delta should be zero for a Pythagorean triplet.
   var delta = Math.abs( ((a*a) + (b*b) - (c*c)) * 100 / (c*c));
   // Return true if a Pythagorean triplet (if delta is small enough).
   return (delta < epsilon);
} // End of the floating-poing check function.

// Type annotation is not used for parameters here. This allows 
// the function to accept both integer and floating-point values 
// without coercing either type.
function checkTriplet(a, b, c) : boolean { 
   // The main triplet checker function.
   // First, move the longest side to position c.
   var d = 0; // Create a temporary variable for swapping values
   if (b > c) { // Swap b and c.
      d = c;
      c = b;
      b = d;
   }
   if (a > c) { // Swap a and c.
      d = c;
      c = a;
      a = d;
   }

   // Test all 3 values. Are they integers?
   if ((int(a) == a) && (int(b) == b) && (int(c) == c)) { // If so, use the precise check.
      return integerCheck(a, b, c); 
   } else { // If not, get as close as is reasonably possible.
      return floatCheck(a, b, c); 
   }
} // End of the triplet check function.

// Test the function with several triplets and print the results.
// Call with a Pythagorean triplet of integers.
print(checkTriplet(3,4,5));
// Call with a Pythagorean triplet of floating-point numbers.
print(checkTriplet(5.0,Math.sqrt(50.0),5.0));
// Call with three integers that do not form a Pythagorean triplet.
print(checkTriplet(5,5,5));

このプログラムの出力は次のようになります。

true
true
false

参照

参照

function ステートメント

その他の技術情報

JScript の関数

JScript のデータ型