사용자 정의 JScript 함수

JScript에는 기본 제공 함수가 많지만 사용자가 직접 원하는 함수를 만들 수도 있습니다. 함수 정의는 함수 문과 JScript 문 블록으로 구성됩니다.

사용자 지정 함수 정의

다음 예제에서 checkTriplet 함수는 삼각형의 변의 길이를 인수로 사용합니다. 세 숫자가 피타고라스 정의(직각 삼각형의 빗변의 길이의 제곱은 다른 두 변 길이의 제곱의 합과 같음)를 만족하는지 검사하여 삼각형이 직각 삼각형인지 확인합니다. checkTriplet 함수는 다른 두 함수 중 하나를 호출하여 실제 검사를 수행합니다.

부동 소수점 테스트에서는 매우 작은 숫자(epsilon)를 테스트 변수로 사용합니다. 부동 소수점을 계산할 때 불확실 오류 및 반올림 오류가 발생할 수 있으므로 세 숫자가 모두 정수가 아닐 경우 피타고라스 정의를 만족하는지 직접 테스트하는 것은 비실용적입니다. 그렇지만 직접 테스트가 더 정확하기 때문에 다음 예제 코드에서는 직접 테스트를 사용하는 것이 적합한 지 확인한 후 사용합니다.

이러한 함수를 정의할 때는 형식 주석을 사용하지 않습니다. 이러한 경우에는 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 데이터 형식