You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Groovy语言整数转罗马数字功能异常问题排查求助

整数转罗马数字功能问题排查与修复

问题背景

尝试用Groovy实现整数转罗马数字,目标转换3569和1234,但输出结果错误。

错误输出

Number: 3569 1000: III
100: V
10: VI
1: IX
Number: 1234 1000: I
100: II
10: III
1: IV

原代码

def emitRNValue(int quotient, int divisor) { 
Map strokes = [1000:['M'],
                500:['D'], 
                100:['C'],
                 50:['L'],
                 10:['X'],
                  5:['V'], 
                  1:['I']] 

def RNList = ['I','II','III','IV','V','VI','VII','VIII','IX','X']
(divisor).each { println "$it: ${RNList[quotient-1]}"}
} 
 
def processNumber(int n) { 
    print "Number: ${n} " 
    int divisor = 1000 
    while (n > 0) { 
       int quotient = n.intdiv(divisor) 
       emitRNValue(quotient,divisor) 
       n = n - quotient * divisor 
       divisor = divisor.intdiv(10) 
    } 
    println() 
} 
processNumber(3569) 
processNumber(1234)

问题排查

  1. 循环逻辑完全错误:(divisor).each会遍历0到divisor-1的所有数值,完全偏离了根据商生成对应罗马数字的需求,导致无意义的重复输出。
  2. 符号映射未区分量级:固定使用RNList中的个位罗马符号,没有区分千、百、十、个不同量级的专属符号(比如百位应该用C、D、M,而非I、V、X)。
  3. 未处理商为0的情况:当某一位商为0时,仍会执行输出逻辑,造成冗余内容。

修复后的代码

def emitRNValue(int quotient, int divisor) {
    // 定义每个量级对应的基础、5倍、10倍符号
    def symbolMap = [
        1000: ['M', '', ''],       // 千位无5倍/10倍符号(罗马数字最大支持到3999)
        100: ['C', 'D', 'M'],
        10: ['X', 'L', 'C'],
        1: ['I', 'V', 'X']
    ]
    
    if (quotient == 0) return  // 商为0时跳过输出
    
    def symbols = symbolMap[divisor]
    def result = ""
    switch(quotient) {
        case 1..3:
            result = symbols[0] * quotient
            break
        case 4:
            result = symbols[0] + symbols[1]
            break
        case 5:
            result = symbols[1]
            break
        case 6..8:
            result = symbols[1] + (symbols[0] * (quotient - 5))
            break
        case 9:
            result = symbols[0] + symbols[2]
            break
    }
    println "${divisor}: ${result}"
}

def processNumber(int n) {
    println "Number: ${n}"
    int divisor = 1000
    while (n > 0) {
        int quotient = n.intdiv(divisor)
        emitRNValue(quotient, divisor)
        n = n - quotient * divisor
        divisor = divisor.intdiv(10)
    }
    println()
}

processNumber(3569)
processNumber(1234)

正确输出

Number: 3569
1000: MMM
100: D
10: LX
1: IX

Number: 1234
1000: M
100: CC
10: XXX
1: IV

内容的提问来源于stack exchange,提问作者Nicky

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 15:40:28