C语言程序将罗马数字转换为十进制数字
下面是使用 C 语言将罗马数字转换为十进制数字的算法:
算法
步骤 1 - 开始
步骤 2 - 在运行时读取罗马数字
步骤 3 - length: = strlen(roman)
步骤 4 - for i = 0 to length-1 do
步骤 4.1 - switch(roman[i])
步骤 4.1.1 - case ‘m’
步骤 4.1.2 - case ‘M’
步骤 4.1.2.1 - d[i]: =1000
步骤 4.1.3 - case ‘d’
步骤 4.1.4 - case ‘D’
步骤 4.1.4.1 - d[i]: =500
步骤 4.1.5 - case ‘c’
步骤 4.1.6 - case ‘C’
步骤 4.1.6.1 - d[i]: =100
步骤 4.1.7 - case ‘l’
步骤 4.1.8 - case ‘L’
步骤 4.1.8.1 - d[i]: =50
步骤 4.1.9 - case ‘x’
步骤 4.1.10 - case ‘X’
步骤 4.1.10.1 - d[i]: =10
步骤 4.1.11 - case ‘v’
步骤 4.1.12 - case ‘V’
步骤 4.1.12.1 - d[i]: =5
步骤 4.1.13 - case ‘i’
步骤 4.1.14 - case ‘I’
步骤 4.1.14.1 - d[i]: =1
步骤 5 - for i =0 to length-1 do
步骤 5.1 - if (i==length-1) or (d[i]>=d[i+1]) then
步骤 5.1.1 - deci += d[i]
步骤 5.2 - else
步骤 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
"); printf("Decimal:.........Roman
"); printf("%5d............%3c
",1,'I'); printf("%5d............%3c
",5,'V'); printf("%5d............%3c
",10,'X'); printf("%5d............%3c
",50,'L'); printf("%5d............%3c
",100,'C'); printf("%5d............%3c
",500,'D'); printf("%5d............%3c
",1000,'M'); printf("Enter a Roman numeral:"); 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 Enter a Roman numeral: M The Decimal equivalent of Roman Numeral M is 1000