用js实现一个加法的方法

/**
 * Adds two numbers together.
 *
 * @param {number} a The first number.
 * @param {number} b The second number.
 * @returns {number} The sum of the two numbers.
 */
function add(a, b) {
  return a + b;
}


// Examples:
console.log(add(2, 3)); // Output: 5
console.log(add(-1, 1)); // Output: 0
console.log(add(0.1, 0.2)); // Output: 0.30000000000000004 (due to floating-point precision)


// Handling potential errors:  More robust version

/**
 * Adds two numbers together, handling non-numeric inputs.
 *
 * @param {number} a The first number.
 * @param {number} b The second number.
 * @returns {number | string} The sum of the two numbers, or an error message if inputs are invalid.
 */
function addSafe(a, b) {
  if (typeof a !== 'number' || typeof b !== 'number') {
    return "Invalid input: Both arguments must be numbers.";
  }
  return a + b;
}

console.log(addSafe(2, 3)); // Output: 5
console.log(addSafe("hello", 3)); // Output: "Invalid input: Both arguments must be numbers."


// Even more robust, handling NaN:

/**
 * Adds two numbers together, handling non-numeric inputs and NaN.
 *
 * @param {number} a The first number.
 * @param {number} b The second number.
 * @returns {number | string} The sum of the two numbers, or an error message if inputs are invalid or result in NaN.
 */
function addRobust(a, b) {
    if (typeof a !== 'number' || typeof b !== 'number') {
        return "Invalid input: Both arguments must be numbers.";
    }
    const sum = a + b;
    if (isNaN(sum)) {
        return "Error: Result is NaN.";
    }
    return sum;
}

console.log(addRobust(2, 3)); // Output: 5
console.log(addRobust(Infinity, -Infinity)); // Output: "Error: Result is NaN."


I've provided three versions:

  1. add(a, b): A simple and straightforward addition function. It's efficient but doesn't handle invalid input.

  2. addSafe(a, b): A safer version that checks if the inputs are numbers and returns an error message if they aren't. This prevents unexpected behavior.

  3. addRobust(a, b): The most robust version. It handles non-numeric inputs and checks for NaN (Not a Number) results, which can occur in certain calculations (like Infinity - Infinity). This provides the most comprehensive error handling.

Choose the version that best suits your needs in terms of simplicity and error handling. For most common cases, addSafe is a good balance. If you anticipate potentially problematic inputs, addRobust is the best choice.

posted @   王铁柱6  阅读(6)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示