给定十进制数字n,我们必须将其转换为罗马数字。n的范围是1到4000。这些是一些罗马数字。
| 数 | 数字 |
|---|---|
| 1个 | 一世 |
| 4 | IV |
| 5 | V |
| 9 | 九 |
| 10 | X |
| 40 | 加大码 |
| 50 | 大号 |
| 90 | XC |
| 100 | C |
| 400 | 光盘 |
| 500 | d |
| 900 | 厘米 |
| 1000 | 中号 |
| 4000 | MMMM |
因此,如果数字n = 859,则其罗马数字将为DCCCLIX
为了解决这个问题,我们将按照以下步骤
定义一个数组,用于存储给定列表的数字和相应的值。那就是所谓的nume数组
我们使用的是递归方法,使用了decToRom()函数。这是nume数组和数字num。
decToRom()就像
如果num不为0,则
max:=从nume数组中找到不大于num的最大值
将最大值的值附加到结果字符串中
num:= num –最大值
decToRom(nume,num)
让我们看下面的实现以更好地理解-
#include<stdio.h>
typedef struct{
char *sym;
int val;
}numeral;
int maxNume(numeral *nu, int num){
int i, index;
for(i = 0; i<15; i++){//15 numerals in array
if(nu[i].val <= num)
index = i;
}
//gretest value numeral index, not greater than number
return index;
}
void decToRoman(numeral *nu, int num){
int max;
if(num != 0){
max = maxNume(nu, num);
printf("%s", nu[max].sym);
num -= nu[max].val;//decrease number
decToRoman(nu, num);//recursively print numerals
}
}
main(){
int number;
numeral nume[15] = {{"I",1},{"IV",4},{"V",5},{"IX",9}, {"X",10},{"XL",40},{"L",50},{"XC",90},
{"C",100},{"CD",400},{"D",500},{"CM",900},{"M",1000},{"MMMM",4000},{"V'",5000}};
printf("Enter a decimal number: ");
scanf("%d", &number);
if(number >0 && number <= 5000){//checking input number
printf("The Roman equivalent of %d is ", number);
decToRoman(nume, number);
}
else{
printf("Invalid Input");
}
printf("\n");
}570 3574
输出结果
DLXX MMMDLXXIV