Please check the below link to know about how to write roman numerals.
Write a C program to convert binary value to roman equivalent.
#include <math.h>
void decimalToRoman(int number) {
printf("Roman Number: ");
while (number > 0) {
if (number >= 1000) {
/* M - 1000 */
printf("M");
number = number - 1000;
} else if (number >= 500) {
/*
* D is 500. CM is 900
* CM = M - C = 1000 - 100 => 900
*/
if (number >= 900) {
printf("CM");
number = number - 900;
} else {
printf("D");
number = number - 500;
}
} else if (number >= 100) {
/*
* C is 100. CD is 400
* CD = D - C = 500 - 100 => 400
*/
if (number >= 400) {
printf("CD");
number = number - 400;
} else {
printf("C");
number = number - 100;
}
} else if (number >= 50) {
/*
* L is 50. XC is 90
* XC = C - X = 100 - 10 => 90
*/
if (number >= 90) {
printf("XC");
number = number - 90;
} else {
printf("L");
number = number - 50;
}
} else if (number >= 9) {
/*
* XL is 40. IX is 9. X is 10
* XL = L - X = 50 - 10 = 40
* IX = X - I = 10 - 1 = 9
*/
if (number >= 40) {
printf("XL");
number = number - 40;
} else if (number == 9) {
printf("IX");
number = number - 9;
} else {
printf("X");
number = number - 10;
}
} else if (number >= 4) {
/*
* V is 5 and IV is 4
* IV = V - I = 5 - 1 => 4
*/
if (number >= 5) {
printf("V");
number = number - 5;
} else {
printf("IV");
number = number - 4;
}
} else {
printf("I");
number = number - 1;
}
}
printf("\n");
}
int value, i = 0, res = 0, remainder;
/* get the input from the user */
printf("Enter your input:");
scanf("%d", &value);
/* convert binary to decimal */
while (value > 0) {
remainder = value % 10;
res = res + (remainder * pow(2, i));
value = value / 10;
i++;
}
/* print the resultant decimal value */
decimalToRoman(res);
return 0;
}
Note:
gcc binaryToRoman.c -lm => link math library since we have used pow() function.
Output:
jp@jp-VirtualBox:~/$ ./a.out
Enter your input:1111
Roman Number: XV
Enter your input:1111
Roman Number: XV
No comments:
Post a Comment