C程序将罗马数字转换为十进制数字

下面给出了一种用 C 语言将罗马数字转换为十进制数字的算法 -

算法

步骤 1 - 开始

步骤 2 - 在运行时读取罗马数字

第 3 步 - 长度:= strlen(roman)

第 4 步 - 对于 i = 0 到 length-1 做

      步骤 4.1 - switch(roman[i])

          步骤 4.1.1 - 案例“m”:

          步骤 4.1.2 - 案例“M”:

               步骤 4.1.2.1 - d[i]: =1000

          步骤 4.1.3 - 案例“d”:

               步骤 4.1.4 - 案例“D”:

          步骤 4.1.4.1 - d[i]:=500

          步骤 4.1.5 - 案例“c”:

               步骤 4.1.6 - 案例“C”:

                   步骤 4.1.6.1 - d[i]: =100

          步骤 4.1.7 - 案例“l”:

          步骤 4.1.8 - 案例“L”:

                   步骤 4.1.8.1 - d[i]:=50

          步骤 4.1.9 - 案例“x”:

          步骤 4.1.10 - 案例“X”:

                   步骤 4.1.10.1 - d[i]: =10

           步骤 4.1.11 - 案例“v”:

          步骤 4.1.12 - 案例“V”:

                步骤 4.1.12.1 - d[i]: =5

          步骤 4.1.13 - 案例“i”:

          步骤 4.1.14 - 案例“I”:

                步骤 4.1.14.1 - d[i]: =1

          第 5 步 - 对于 i =0 到 length-1 做

                步骤 5.1 - 如果 (i==length-1) 或 (d[i]>=d[i+1]) 那么

                      步骤 5.1.1 - deci += d[i]

          步骤 5.2 - 其他

              步骤 5.2.1 - deci -= d[i]

步骤 6 - 打印罗马数字的十进制等效值

步骤 7 - 停止

程序

以下是将罗马数字转换为十进制数字的 C 程序-

#include <stdio.h>
#include <conio.h>
main(){
   char roman[30];
   int deci=0;
   int length,i,d[30];
   printf("The Roman equivalent to decimal\n");
   printf("Decimal:.........Roman\n");
   printf("%5d............%3c\n",1,'I');
   printf("%5d............%3c\n",5,'V');
   printf("%5d............%3c\n",10,'X');
   printf("%5d............%3c\n",50,'L');
   printf("%5d............%3c\n",100,'C');
   printf("%5d............%3c\n",500,'D');
   printf("%5d............%3c\n",1000,'M');
   printf("输入罗马数字:");
   scanf("%s",roman);
   length=strlen(roman);
   for(i=0;i<length;i++){
      switch(roman[i]){
         case 'm':
         case 'M': d[i]=1000; break;
         case 'd':
         case 'D': d[i]= 500; break;
         case 'c':
         case 'C': d[i]= 100; break;
         case 'l':
         case 'L': d[i]= 50; break;
         case 'x':
         case 'X': d[i]= 10; break;;
         case 'v':
         case 'V': d[i]= 5; break;
         case 'i':
         case 'I': d[i]= 1;
      }
   }
   for(i=0;i<length;i++){
      if(i==length-1 || d[i]>=d[i+1])
         deci += d[i];
      else
         deci -= d[i];
   }
   printf("The Decimal equivalent of Roman numeral %s is %d", roman, deci);
}
输出结果

执行上述程序时,会产生以下结果 -

The Roman equivalent to decimal
Decimal:.........Roman
1............ I
5............ V
10............ X
50............ L
100............ C
500............ D
1000............ M
输入罗马数字: M
The Decimal equivalent of Roman Numeral M is 1000