MST

星途 面试题库

面试题:Rust位置参数在控制台复杂运算及错误处理

编写一个Rust程序,该程序接受三个位置参数。第一个参数表示运算符(如'+', '-', '*', '/'),后两个参数为操作数。程序需要根据运算符对操作数进行相应运算并输出结果。要求实现合理的错误处理,例如参数数量不对、操作数无法解析为数字、除数为零等情况,并给出清晰的错误提示。
12.6万 热度难度
编程语言Rust

知识考点

AI 面试

面试题答案

一键面试
use std::env;

fn main() {
    let args: Vec<String> = env::args().collect();
    if args.len() != 4 {
        eprintln!("Usage: {} <operator> <operand1> <operand2>", args[0]);
        return;
    }

    let operator = &args[1];
    let operand1: f64;
    let operand2: f64;
    match (args[2].parse(), args[3].parse()) {
        (Ok(num1), Ok(num2)) => {
            operand1 = num1;
            operand2 = num2;
        },
        (Err(_), _) => {
            eprintln!("Both operands must be numbers.");
            return;
        }
    }

    let result = match operator {
        "+" => operand1 + operand2,
        "-" => operand1 - operand2,
        "*" => operand1 * operand2,
        "/" => {
            if operand2 == 0.0 {
                eprintln!("Division by zero is not allowed.");
                return;
            }
            operand1 / operand2
        }
        _ => {
            eprintln!("Unsupported operator: {}", operator);
            return;
        }
    };

    println!("Result: {}", result);
}