1 solutions

  • 0
    @ 2025-2-8 13:11:00
    #include<stdio.h>
    #include<string.h>
    #include<stdlib.h>
    #include<math.h>
    
    //初始化从1000到1的数值与符号的列表对
    const int value[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
    const char* symbol[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
    
    int main(){
        int num;
        scanf("%d",&num);
    
        //初始化答案字符串
        char* ans = malloc(sizeof(char) * 16);
        ans[0] = '\0';
    
        //循环遍历数值列表对,将num转换为罗马数字
        for (int i = 0; i < 13; i++) {
            while (num >= value[i]) {
                num -= value[i];
                //将当前符号添加到答案字符串中,使用strcpy函数将symbol[i]复制到ans的末尾
                strcpy(ans + strlen(ans), symbol[i]);
            }
            if (num == 0) {
                break;
            }
        }
        printf("%s",ans);
        return 0;
    }
    
    • 1