首页 > 其他分享 >输入一个四则混合运算的表达式,请写个方法求它的值

输入一个四则混合运算的表达式,请写个方法求它的值

时间:2024-12-10 09:22:52浏览次数:9  
标签:function peek 写个 return 运算 console expression 表达式 log

function evaluateExpression(expression) {
  try {
    // Use eval() for simplicity, but be cautious in production environments.
    // Consider using a dedicated expression parser for better security and error handling.
    const result = eval(expression);
    if (isNaN(result) || !isFinite(result)) {
      return "Invalid expression"; // Handle cases like division by zero or invalid input
    }
    return result;
  } catch (error) {
    return "Invalid expression"; // Handle syntax errors
  }
}


// Examples:
console.log(evaluateExpression("10 + 5 * 2 - 3 / 3")); // Output: 19
console.log(evaluateExpression("2 * (5 + 3)")); // Output: 16
console.log(evaluateExpression("10 / 0")); // Output: Invalid expression
console.log(evaluateExpression("1 + a")); // Output: Invalid expression



// More robust solution using a simple recursive descent parser (handles +, -, *, /, parentheses):

function evaluateExpressionRobust(expression) {
  let index = 0;

  function peek() {
    return expression[index];
  }

  function consume(char) {
    if (peek() !== char) {
      throw new Error("Unexpected character: " + peek());
    }
    index++;
  }

  function parseNumber() {
    let numStr = "";
    while (index < expression.length && (/\d|\./).test(peek())) {
      numStr += peek();
      index++;
    }
    return parseFloat(numStr);
  }

  function parseFactor() {
    if (peek() === '(') {
      consume('(');
      const result = parseExpression();
      consume(')');
      return result;
    } else {
      return parseNumber();
    }
  }

  function parseTerm() {
    let left = parseFactor();
    while (peek() === '*' || peek() === '/') {
      const operator = peek();
      consume(operator);
      const right = parseFactor();
      if (operator === '*') {
        left *= right;
      } else {
        left /= right;
      }
    }
    return left;
  }

  function parseExpression() {
    let left = parseTerm();
    while (peek() === '+' || peek() === '-') {
      const operator = peek();
      consume(operator);
      const right = parseTerm();
      if (operator === '+') {
        left += right;
      } else {
        left -= right;
      }
    }
    return left;
  }

  try {
    const result = parseExpression();
    if (index !== expression.length) {  // Check for unconsumed characters
      throw new Error("Invalid expression: trailing characters");
    }
    return result;
  } catch (error) {
    return "Invalid expression: " + error.message;
  }
}



// Robust examples
console.log(evaluateExpressionRobust("10 + 5 * 2 - 3 / 3")); // Output: 19
console.log(evaluateExpressionRobust("2 * (5 + 3)")); // Output: 16
console.log(evaluateExpressionRobust("10 / 0")); // Output: Invalid expression: Division by zero  (Note improved error message)
console.log(evaluateExpressionRobust("1 + a")); // Output: Invalid expression: Unexpected character: a
console.log(evaluateExpressionRobust("1 + 2)")); // Output: Invalid expression: Unexpected character: )



Explanation and Improvements:

  1. eval() - Simple but Risky: The first evaluateExpression function uses eval(). This is concise, but presents security risks if the expression comes from user input (as malicious code could be injected). Avoid eval() in production if possible.

  2. Robust Parser: The evaluateExpressionRobust function demonstrates a basic recursive descent parser. This is a much safer and more controlled way to evaluate expressions. It handles operator precedence (multiplication/division before addition/subtraction) and parentheses correctly. It also provides more informative error messages.

  3. Error Handling: Both functions include error handling to catch invalid input (like division by zero or incorrect syntax). The robust version provides more specific error messages.

  4. Recursive Descent Parsing: The robust parser uses a common technique for parsing expressions. It breaks the problem down into smaller parts (factors, terms, expressions) and recursively calls itself to handle nested expressions and operator precedence

标签:function,peek,写个,return,运算,console,expression,表达式,log
From: https://www.cnblogs.com/ai888/p/18596567

相关文章

  • Python位运算
    BitwiseOperationsinPython:APowerfulToolforManipulatingBinaryData在Python中,位运算是一种强大的工具,可用于操作二进制数据。它具有执行各种算术和逻辑操作的能力,为各种计算问题提供了广泛的解决方案。位运算在Python中的一个关键优势是它们的灵活性。内置的位运算......
  • 给定特定的字符串,写个方法判断是否以元字母结尾
    functionendsWithVowel(str){if(!str||str.length===0){returnfalse;//Orhandleemptystringsasneeded}constvowels="aeiouAEIOU";constlastChar=str.charAt(str.length-1);returnvowels.includes(lastChar);}//......
  • 运算符
          ......
  • 运算符和表达式
            ......
  • .NET正则表达式
    正则表达式提供了功能强大、灵活而又高效的方法来处理文本。正则表达式丰富的泛模式匹配表示法使你可以快速分析大量文本,以便:查找特定字符模式。验证文本以确保它匹配预定义模式(如电子邮件地址)。提取、编辑、替换或删除文本子字符串。将提取的字符串添加到集合中,以便......
  • JS-7 typeof 运算符
    数值:number、字符串:string、布尔值:bookan、对象:objectJavaScript有三种方法,可以确定一个值到底是什么类型,而我们现在需要接触到的就是typeof1、数值返回numbertypeo123//"number"2、字符串返回stringtypeof'123'//"string"3、布尔值返回booleantypeof......
  • 【C++算法】35.位运算_两整数之和
    文章目录题目链接:题目描述:解法C++算法代码:题目链接:371.两整数之和题目描述:解法笔试的话直接returna+b;接下来讲一下这题的解法:位运算(异或运算-无进位相加)例如:13和2813+28=4113的二进制位a:00110128的二进制位b:011100a^b:010001因为异或运算是无进......
  • 【C++算法】36.位运算_只出现一次的数字 II
    文章目录题目链接:题目描述:解法C++算法代码:解析题目链接:137.只出现一次的数字II题目描述:解法你必须设计并实现线性时间复杂度的算法且使用常数级空间来解决此问题。说明时间复杂度O(n),空间复杂度O(1)意外发现出现1次的那个数和所有比特位当前的和%3得......
  • 正则表达式合集
    干货一.校验数字数字:^[0-9]*$n位的数字:^\d{n}$至少n位的数字:^\d{n,}$m-n位的数字:^\d{m,n}$零和非零开头的数字:^(0|[1-9][0-9]*)$非零开头的最多带两位小数的数字:^([1-9][0-9]*)+(.[0-9]{1,2})?$带1-2位小数的正数或负数:^(\-)?\d+(\.\d{1,2})?$正数、负数、和小数:^(\-|\+......
  • Python语言基础(四):运算符、基本输入和输出
    前言:在Python的编程世界中,运算符以及基本输入和输出是构建程序的重要组成部分。熟练掌握它们,能让你更自如地编写各类Python程序。本章,我们将深入对其进行探讨,助力你的Python学习进程。在本章中,我们将逐步揭开以下主题的神秘面纱:运算符:学习Python中的算术、比较、逻辑等运算符,......