Skip to content

简单 Calculator

简单 约 20 分钟

你将构建什么

`calculate(, op, b)` 函数那个 supports +, -, *, / and 返回 numeric result, 使用 guard 针对 division 通过零.

学习目标

  • 定义函数使用多个参数
  • Use conditional or match 到选择操作
  • 返回值 从函数
  • Handle 边缘情况 (division 通过零)

前置要求

  • 变量 and 数据类型 (数字)
  • 如果/else or 切换/match 语句
  • 函数定义概念

步骤

  1. 1

    定义函数 signature

    创建函数 calculate(, op, b) 哪里 ` and b 是数字 and op` 是字符串如 "+", "-", "*", "/". signature tells caller 精确地什么到 provide.

    代码
    function calculate(a, op, b) {
      // body comes next
    }

    预期结果

    函数 exists and 能是 called, 但返回无 yet.

  2. 2

    选择操作

    内部函数, 分支 on op and 执行 matching arithmetic. Returning 内部每个分支 keeps logic flat and readable.

    代码
      if (op === "+") return a + b;
      if (op === "-") return a - b;
      if (op === "*") return a * b;
      if (op === "/") return a / b;

    预期结果

    Calling calculate(4, "+", 5) 返回 9; calculate(10, "*", 3) 返回 30.

  3. 3

    Guard division 通过零

    之前划分, 检查 whether b === 0 and 返回 safe 值 or 消息. 这个 prevents 无穷大 or 运行时错误从 leaking 到 caller.

    代码
      if (op === "/") {
        if (b === 0) return "Cannot divide by zero";
        return a / b;
      }

    预期结果

    calculate(5, "/", 0) 返回错误消息相反的 无穷大.

  4. 4

    测试所有运算符

    Call 函数一次 for 每个运算符 and print results. 测试每个分支是 如何你 确认函数是 完整.

    代码
    console.log(calculate(4, "+", 5));  // 9
    console.log(calculate(10, "-", 3)); // 7
    console.log(calculate(6, "*", 7));  // 42
    console.log(calculate(8, "/", 2));  // 4
    console.log(calculate(5, "/", 0));  // Cannot divide by zero

    预期结果

    Five 行的 输出: 9, 7, 42, 4, and division-通过-零消息.

  5. 5

    添加输入验证

    在主逻辑入口处添加输入验证:检查输入是否为有效数字、是否在允许范围内,对非法输入给出清晰提示而非崩溃。这是健壮程序的第一道防线。

    代码
    function validateInput(value, min, max) {
      if (typeof value !== "number" || Number.isNaN(value)) {
        throw new Error(`Invalid input: ${value} is not a number`);
      }
      if (value < min || value > max) {
        throw new Error(`Input ${value} out of range [${min}, ${max}]`);
      }
      return value;
    }
    
    // Usage
    const input = validateInput(rawInput, 1, 100);

    预期结果

    非法输入(非数字或超出范围)会抛出清晰的错误信息,合法输入正常通过。

自己动手试试

你学到了什么

你构建函数那个接受参数, 分支 on 输入, 返回值, and handles 边缘情况 — four ingredients 的大多数真实函数.

相关资源

相关课程

  • 函数

    如何 定义 and call 函数使用参数.

  • 条件

    Branching 使用如果语句, used 到选择运算符.

相关练习

相关工具

  • Math Evaluator

    Compare 你的 calculator 使用完整表达式 evaluator.

相关速查表

相关参考文档

相关错误

相关术语

相关术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

相关错误

用大白话解释常见错误——什么意思、为什么发生、如何修复。

← 返回主题