算数表达式

算数表达式

算数运算符
  1. +:两边操作符都是数字才相加,其余情况都是连字符
  2. /
  3. %

隐式类型转换
如果参与数学运算的某操作数不是数字类型,会自动将此操作数转为数字类型(本质是在内部调用Number函数将对应的值转换成数字类型)

有关IEEE754
解决办法:在进行小数运算时,要调用数字的toFixed方法,保留指定的小数位数
负数没有开根号,所以为NaN

关系表达式

关系运算符:关系运算符运算结果是布尔值
  1. <
  2. =

  3. <=
  4. ==
  5. !==
  6. ===
  7. !=

相等和全等

  • 相等:两个等号不比较值的类型,它会进行隐式转换后比较值是否相等
  • 全等:三个等号不仅比较值相同也比较类型相同
  • null和undefined用==进行比较(涉及隐式强制类型转换,ES5规范中规定)
    如果x为null,y为undefined,则结果为true;如果x为null,y为undefined,则结果为true
  • null和undefined用===进行比较时结果为false是因为类型不同
typeof null  //object
typeof undefined //undefined
NaN==NaN //false
NaN===NaN //false

如何判断是否为NaN:isNaN()

逻辑表达式

逻辑运算符
  1. &&
  2. ||

短路计算
a&&b运算中:a真,表达式的值为b;a假,表达式的值为a
a||b运算中:a真,表达式的值为a;a假,表达式的值为b
逻辑运算顺序:非----与----或

赋值表达式

赋值运算符
  1. =
  2. +=
  3. -=
  4. *=
  5. /=
  6. %=
  7. ++
综合表达式

运算顺序:非运算----数学运算----关系运算----逻辑运算

变量的范围表示

// 5<=a<=12
if(a>=5&&a<=12){}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
堆栈可以用来实现算数表达式的计算。 具体实现步骤如下: 1. 创建一个操作数栈和一个操作符栈。 2. 从左到右遍历表达式,对于每个字符: - 如果它是一个数字,则将其压入操作数栈。 - 如果它是一个操作符,则将其压入操作符栈。 - 如果它是一个右括号,则弹出操作符栈中的操作符和操作数栈中的操作数,直到遇到左括号为止。然后将计算结果压入操作数栈。 3. 最后,操作符栈中可能还有操作符,需要按照优先级顺序弹出操作符并计算,直到操作符栈为空。最后的操作数栈中的元素即为表达式的计算结果。 下面是一个示例代码,实现了一个简单的算数表达式计算器: ```python class Stack: def __init__(self): self.items = [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[-1] def is_empty(self): return len(self.items) == 0 def calculate(expression): precedence = {'+': 1, '-': 1, '*': 2, '/': 2, '(': 0, ')': 0} operand_stack = Stack() operator_stack = Stack() for token in expression: if token.isdigit(): operand_stack.push(int(token)) elif token in '+-*/': while not operator_stack.is_empty() and precedence[token] <= precedence[operator_stack.peek()]: operator = operator_stack.pop() operand2 = operand_stack.pop() operand1 = operand_stack.pop() result = eval(f'{operand1} {operator} {operand2}') operand_stack.push(result) operator_stack.push(token) elif token == '(': operator_stack.push(token) elif token == ')': while operator_stack.peek() != '(': operator = operator_stack.pop() operand2 = operand_stack.pop() operand1 = operand_stack.pop() result = eval(f'{operand1} {operator} {operand2}') operand_stack.push(result) operator_stack.pop() while not operator_stack.is_empty(): operator = operator_stack.pop() operand2 = operand_stack.pop() operand1 = operand_stack.pop() result = eval(f'{operand1} {operator} {operand2}') operand_stack.push(result) return operand_stack.pop() expression = '2 * (3 + 4) - 5 / 2' result = calculate(expression) print(f'{expression} = {result}') ``` 输出结果为: ``` 2 * (3 + 4) - 5 / 2 = 13.5 ``` 注意,这个实现只支持整数和四则运算,没有处理错误输入和除数为0的情况。在实际应用中,需要加入更多的判断和处理逻辑。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值