如何在没有外部机箱的情况下将字符串表达式转换和计算为算术表达式



如何在没有外部机箱的情况下将字符串表达式转换和计算为算术表达式例如:"500+10-6*32"。预期结果=14208(不希望操作员的优先级(

//a = ‘+’, b = ‘-’, c = ‘*’, d = ‘/’, e = ‘(’, f = ‘)’
use std::collections::VecDeque;
fn calculate(s: String) -> i32 {
let mut multi_active = false;
const SPACE: char = ' ';
const SIGN_PLUS: char = '+';
const SIGN_MINUS: char = '-';
const SIGN_MULTIPLY: char = '*';
const SIGN_DIVIDE: char = '/';
const PAREN_OPEN: char = '(';
const PAREN_CLOSED: char = ')';
let len_s: usize = s.len();
let mut num: i32 = 0;
let mut ans: i32 = 0;
let mut sign: i32 = 1;
let mut stk: VecDeque<i32> = VecDeque::with_capacity(len_s);
stk.push_back(sign);
for ch in s.chars() {
println!("chars:{}",ch);
match ch {
'0'.. => {
num = num * 10 + (ch as i32 - '0' as i32);
println!("given numbers:{num}");
}
SIGN_PLUS | SIGN_MINUS => {
// println!("b4 ans = {ans}");
// println!("b4 sig = {sign}");
// println!("b4 num = {num}");
ans += sign * num;
sign = stk.back().unwrap() * if ch == SIGN_PLUS { 1 } else { -1 };
num = 0;
// println!("addition ans  = {ans}");
// println!("multiply sig = {sign}");
// println!("multiply num = {num}");
multi_active = false;
}
PAREN_OPEN => {
stk.push_back(sign);
// println!("brak open");
// multi_active = false;
}
PAREN_CLOSED => {
stk.pop_back();
// multi_active = false;
}
SIGN_MULTIPLY => {
println!("b4 ans = {ans}"); //0  always
println!("b4 sig = {sign}"); // 1 always
println!("b4 num = {num}");// 10 first number
// 10 = 0 + 1 * 10

ans = ans + sign * num; // current ans = 10 target=>27
println!("simple multi- {}", ans);
//ans=3;
sign = stk.back().unwrap() * if ch == SIGN_MULTIPLY { 1 } else { -1 };
num = 0;
// println!("multiply ans = {ans}");
// println!("multiply sig = {sign}");
// println!("multiply num = {num}");
multi_active = true;


}
_ => {}
}
}
println!("final:{ans}@@@@{sign}@@@@{num}===={:?}",multi_active);
// if multi_active {
//    // ans = (ans-3)*num+ 3;
//   ans= ans*num;
// }

// else{
ans = ans + sign * num;
//}
ans
}
fn main() {
let inputs = "2+44+6+1".to_owned();
let outs = calculate(inputs);
println!("{outs}");
}
Expected Results

Input: “500+10-66*32”
Result: 14208

我已经成功地实现了加法和减法,现在坚持从左到右的优先顺序。

这是一个穷人的计算器。没有负值,没有运算符优先级,没有括号,也没有优雅的错误处理;使用风险自负:

fn main() {
let e = "500+10-66*32";

let ops = ['+', '-', '*', '/'];
let values: Vec<f64> = e.split(&ops).map(|v| v.trim().parse().unwrap()).collect();
let operands: Vec<_> = e.matches(&ops).collect();

let (&(mut curr), values) = values.split_first().unwrap();
for (op, &value) in operands.into_iter().zip(values) {
match op {
"+" => { curr = curr + value },
"-" => { curr = curr - value },
"*" => { curr = curr * value },
"/" => { curr = curr / value },
_ => unreachable!(),
}
}

println!("{}", curr);
}
14208

除了一些编译错误(空字符''(。你没有做算术的代码。你在做词汇操作。

我会给更多的建议,但被困惑所阻止。我不知道你想用ab等做什么

最新更新