1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
// Define a module for the calculator
mod calculator {
// Function to add two numbers
/// Adds one to the number given.
///
/// # Examples
///
/// ```
/// let arg = 5;
/// let answer = hellocalc::add(5.0,6.0);
///
/// assert_eq!(11.0, answer);
/// ```
pub fn add(num1: f64, num2: f64) -> f64 {
num1 + num2
}
// Function to subtract two numbers
pub fn subtract(num1: f64, num2: f64) -> f64 {
num1 - num2
}
// Function to multiply two numbers
pub fn multiply(num1: f64, num2: f64) -> f64 {
num1 * num2
}
// Function to divide two numbers
pub fn divide(num1: f64, num2: f64) -> Result<f64, &'static str> {
if num2 == 0.0 {
panic!("Error: Division by zero");
//Err("Division by zero")
} else {
Ok(num1 / num2)
}
}
}
// Export the functions for external use
pub use calculator::*;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_add() {
assert_eq!(add(3.0, 2.0), 5.0);
assert_eq!(add(-3.0, 2.0), -1.0);
assert_eq!(add(0.0, 0.0), 0.0);
}
#[test]
// #[ignore]
fn test_subtract() {
assert_eq!(subtract(3.0, 2.0), 1.0);
assert_eq!(subtract(-3.0, 2.0), -5.0);
assert_eq!(subtract(0.0, 0.0), 0.0);
}
#[test]
fn test_multiply() {
assert_eq!(multiply(3.0, 2.0), 6.0);
assert_eq!(multiply(-3.0, 2.0), -6.0);
assert_eq!(multiply(0.0, 0.0), 0.0);
}
#[test]
fn test_divide() {
assert_eq!(divide(6.0, 2.0), Ok(3.0));
// assert_eq!(divide(3.0, 0.0), Err("Error: Division by zero"));
}
#[test]
#[should_panic]
fn test_divide_by_zero_panics() {
let _ = divide(6.0, 0.0);
}
}