One bracket is working

This commit is contained in:
Alexandre Stein 2022-12-09 15:52:01 +01:00
parent 26601e548e
commit cf9ee27149
1 changed files with 24 additions and 3 deletions

View File

@ -66,7 +66,6 @@ impl TmpNum {
}
// Returns the float number from the parsed input
fn get(&mut self) -> f64 {
println!("XXX {}", self.s);
let n = self.s.parse::<f64>().ok().expect("number is malformed");
self.s = String::new();
@ -147,7 +146,10 @@ fn parse(pattern: String) -> (Vec<Symbol>, Vec<f64>) {
i = i2;
// Check the symbol after the closing bracket
let c3 = pattern.chars().nth(i2 + 1).expect("some char");
let c3 = match pattern.chars().nth(i2 + 1){
Some(c) => c,
None => break,
};
if !c3.is_numeric() {
let s2 = match c3 {
'-' => Some(Symbol::Minus),
@ -322,7 +324,6 @@ fn main() {
process::exit(2);
}
let res = calculation(symbols, numbers);
println!("{res}");
}
@ -356,4 +357,24 @@ mod tests {
let (s, n) = parse("30/4-9".to_string());
assert_eq!(calculation(s, n), -1.5);
}
#[test]
fn negative_number() {
let (s, n) = parse("-2*4+4".to_string());
assert_eq!(calculation(s, n), -4.0);
let (s, n) = parse("-2+2*4".to_string());
assert_eq!(calculation(s, n), 6.0);
}
#[test]
fn with_1_bracket_set() {
let (s, n) = parse("2*(4+4)*2".to_string());
assert_eq!(calculation(s, n), 32.0);
let (s, n) = parse("2*(4+4)".to_string());
assert_eq!(calculation(s, n), 16.0);
let (s, n) = parse("-2*(4+4)".to_string());
assert_eq!(calculation(s, n), -16.0);
let (s, n) = parse("(4+4)*2".to_string());
assert_eq!(calculation(s, n), 16.0);
}
}