← 中文资源

简体中文版本

罗马数字双向转换

从大到小逐档扣减编码罗马数字,解码用 match 映射符号值并处理减法记法;非法字符在 collect::<Result> 里短路报错。

阅读英文原文

实现说明

罗马数字双向转换以函数 to_roman、from_roman、main为骨架。 循环只出现在 for (amount, symbol) in table,它的每次迭代处理一个元素。Result 是错误通道:调用方拿到的是作为值的失败,而不是异常。输入的每种形态各占一个 match 分支,编译器检查这套分支是否完整。

使用要点

  • Result 是唯一的错误通道——改编时删掉一个 ?,那个位置就得显式 match。
  • 跑完文件,输出里会留下标记——bad:。
  • main 按顺序串起 to_roman、from_roman;运行文件就会把这个流程跑一遍。

常见问题

代码如何报告失败?

以 Result 值上报——每个可能失败的调用都返回一个,由调用方 match 或继续传播。

运行「罗马数字双向转换」会打印什么?

文件本身就是完整程序,直接运行——输出行带有 bad: 这类标签。

签名一览:fn to_roman(mut value: u16) -> String

核心语句

.map(|c| values(c).ok_or_else(|| format!("invalid numeral {c:?}")))
.collect::<Result<_, _>>()?;
for (index, value) in chars.iter().enumerate() {
    if let Some(next) = chars.get(index + 1) {
        if next > value {
            total -= value;
            continue;
        }
    }
    total += value;
}
let values = |c: char| match c {
    'I' => Some(1),
    'V' => Some(5),
    'X' => Some(10),
    'L' => Some(50),
    'C' => Some(100),
    'D' => Some(500),
    'M' => Some(1000),
    _ => None,
};

代码示例

fn to_roman(mut value: u16) -> String {
    // 从大到小逐档扣减:数值到符号的有序映射
    let table = [
        (1000, "M"), (900, "CM"), (500, "D"), (400, "CD"),
        (100, "C"), (90, "XC"), (50, "L"), (40, "XL"),
        (10, "X"), (9, "IX"), (5, "V"), (4, "IV"), (1, "I"),
    ];
    let mut out = String::new();
    for (amount, symbol) in table {
        while value >= amount {
            out.push_str(symbol);
            value -= amount;
        }
    }
    out
}

fn from_roman(input: &str) -> Result<u16, String> {
    let values = |c: char| match c {
        'I' => Some(1),
        'V' => Some(5),
        'X' => Some(10),
        'L' => Some(50),
        'C' => Some(100),
        'D' => Some(500),
        'M' => Some(1000),
        _ => None,
    };
    let chars: Vec<u16> = input
        .chars()
        .map(|c| values(c).ok_or_else(|| format!("invalid numeral {c:?}")))
        .collect::<Result<_, _>>()?;
    // 减法记法:小值在大值之前时做减
    let mut total = 0;
    for (index, value) in chars.iter().enumerate() {
        if let Some(next) = chars.get(index + 1) {
            if next > value {
                total -= value;
                continue;
            }
        }
        total += value;
    }
    Ok(total)
}

fn main() {
    for year in [2026, 1994, 44, 9] {
        let roman = to_roman(year);
        println!("{year} -> {roman} -> {}", from_roman(&roman).unwrap());
    }
    println!("bad: {:?}", from_roman("XMZ"));
}