rpn(1): added modulo

This commit is contained in:
Emma Tebibyte 2024-02-01 01:26:48 -07:00
parent 5debb9d954
commit 5f8e90b592
Signed by: emma
GPG Key ID: 06FA419A1698C270

View File

@ -50,7 +50,7 @@ use std::{
process::ExitCode,
};
use CalcType::{ Add, Divide, Multiply, Power, Subtract, Val };
use CalcType::{ Add, Divide, Modulo, Multiply, Power, Subtract, Val };
extern crate sysexits;
@ -64,6 +64,7 @@ enum CalcType {
Multiply,
Divide,
Power,
Modulo,
Val(f64),
}
@ -100,6 +101,7 @@ fn str_to_calc_type(string: &str) -> Option<CalcType> {
"*" => Some(Multiply),
"/" => Some(Divide),
"^" => Some(Power),
"%" => Some(Modulo),
_ => None,
}
}
@ -130,15 +132,16 @@ fn eval(
};
match x {
Add | Divide | Multiply | Power | Subtract => ops.push_back(x),
Add | Divide | Multiply | Power | Subtract | Modulo => {
ops.push_back(x)
},
Val(x_) => stack.push_back(x_),
}
}
for op in &ops {
match op {
Add | Subtract | Multiply | Divide | Power => {
Add | Subtract | Multiply | Divide | Power | Modulo => {
let x = &stack.pop_back().ok_or(EvaluationError {
message: "Stack is empty.".to_string(),
})?;
@ -148,22 +151,12 @@ fn eval(
})?;
match op {
Add => {
&stack.push_back(y + x)
},
Subtract => {
&stack.push_back(y - x)
},
Multiply => {
&stack.push_back(y * x)
},
Divide => {
&stack.push_back(y / x)
},
Power => {
let result = x.powf(*y);
&stack.push_back(result)
},
Add => &stack.push_back(y + x),
Subtract => &stack.push_back(y - x),
Multiply => &stack.push_back(y * x),
Divide => &stack.push_back(y / x),
Power => &stack.push_back(x.powf(*y)),
Modulo => &stack.push_back(y % x),
_ => &{},
};
},