You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为基于readline-sync的Node.js简易计算器添加循环,支持用户重复使用直至选择退出

如何为基于readline-sync的Node.js简易计算器添加循环,支持用户重复使用直至选择退出

嘿,这个需求太常见啦!咱们用do-while循环就能完美实现——它刚好适配这种「至少执行一次操作,再根据用户选择决定是否继续」的场景。我帮你调整代码,同时还优化了几个小细节提升体验,一起来看看~

核心思路

把完整的计算器流程(选操作、输数字、计算结果)包在循环里,每次计算完成后询问用户是否继续,根据回答判断是否再次执行循环。同时还要处理用户输入的有效性,比如支持大小写的「y/yes」来继续,「n/no」来退出。

修改后的完整代码

const calculator = require('readline-sync');

let operations = ['+', '-', '*', '/'];
let operator = null;
let firstNumber = 0;
let secondNumber = 0;

// 完成一次完整的计算流程:选操作→输数字→计算输出
function operationQuestion(){
    // 用while循环替代原递归,避免多次错误输入导致调用栈溢出
    do {
        operator = calculator.question(
            "What operation would you like to perform?\nOptions:\n" +
            `Addition (${operations[0]})\n` +
            `Subtraction (${operations[1]})\n` +
            `Multiplication (${operations[2]})\n` +
            `Division (${operations[3]})\n`
        );
        if (!operations.includes(operator)) {
            console.log("That is not a valid operation, please try again.");
        }
    } while (!operations.includes(operator));

    // 获取两个数字(用questionInt确保输入是整数)
    firstNumber = calculator.questionInt("Type the first number: ");
    secondNumber = calculator.questionInt("Type the second number: ");

    // 执行对应计算并输出结果
    switch(operator) {
        case '+':
            console.log(`The result of ${firstNumber}${operator}${secondNumber} = ${firstNumber + secondNumber}`);
            break;
        case '-':
            console.log(`The result of ${firstNumber}${operator}${secondNumber} = ${firstNumber - secondNumber}`);
            break; 
        case '*':
            console.log(`The result of ${firstNumber}${operator}${secondNumber} = ${firstNumber * secondNumber}`);
            break;   
        case '/':
            // 新增除数为0的校验,避免出现无意义的Infinity结果
            if (secondNumber === 0) {
                console.log("Error: Cannot divide by zero!");
                return;
            }
            console.log(`The result of ${firstNumber}${operator}${secondNumber} = ${firstNumber / secondNumber}`);
            break;
        default:
            console.log("Something went wrong :(");
    }
}

// 循环控制:至少执行一次计算,再根据用户选择决定是否继续
let continueCalculating;
do {
    operationQuestion();
    // 询问是否继续,统一转小写方便判断
    continueCalculating = calculator.question("\nDo you want to perform another calculation? (y/n): ").toLowerCase();
    // 校验用户输入,直到输入有效选项
    while (!['y', 'n', 'yes', 'no'].includes(continueCalculating)) {
        console.log("Please enter a valid response (y/n or yes/no)");
        continueCalculating = calculator.question("Do you want to perform another calculation? (y/n): ").toLowerCase();
    }
// 当用户输入y或yes时,继续循环
} while (continueCalculating === 'y' || continueCalculating === 'yes');

console.log("Thanks for using the calculator! Bye~");

关键修改点说明

  1. do-while循环包裹核心流程:先执行一次计算器操作,再询问用户是否继续,完全符合需求场景。
  2. 替换递归为while循环处理无效操作:原代码的递归调用在多次错误输入后会累积调用栈,改用while循环更健壮,不会出现栈溢出问题。
  3. 优化输入校验与用户体验:
    • 对「是否继续」的输入做了严格校验,只接受y/n/yes/no,避免无效输入导致逻辑混乱。
    • 除法操作时新增了除数为0的判断,友好提示用户错误,而不是输出无意义的Infinity。
  4. 模板字符串简化代码:用`...`替代原有的字符串拼接,代码更简洁易读,减少出错概率。

额外小提示

如果想让计算器支持浮点数计算,只需要把questionInt改成questionFloat就行,这样用户就能输入小数啦~

备注:内容来源于stack exchange,提问作者Ruby Pepper

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.13 17:58:08