Please check the below link know how to write roman numerals.
Write a C program to convert octal value to roman equivalent.
#include <math.h>
#include <string.h>
/* converts given decimal value to roman equivalent */
void decimalToRoman(int input) {
printf("Roman Number: ");
while (input > 0) {
if (input >= 1000) {
/* M - 1000 */
printf("M");
input = input - 1000;
} else if (input >= 500) {
/*
* D is 500. CM is 900
* CM = M - C = 1000 - 100 => 900
*/
if (input >= 900) {
printf("CM");
input = input - 900;
} else {
printf("D");
input = input - 500;
}
} else if (input >= 100) {
/*
* C is 100. CD is 400
* CD = D - C = 500 - 100 => 400
*/
if (input >= 400) {
printf("CD");
input = input - 400;
} else {
printf("C");
input = input - 100;
}
} else if (input >= 50) {
/*
* L is 50. XC is 90
* XC = C - X = 100 - 10 => 90
*/
if (input >= 90) {
printf("XC");
input = input - 90;
} else {
printf("L");
input = input - 50;
}
} else if (input >= 9) {
/*
* XL is 40. IX is 9. X is 10
* XL = L - X = 50 - 10 = 40
* IX = X - I = 10 - 1 = 9
*/
if (input >= 40) {
printf("XL");
input = input - 40;
} else if (input == 9) {
printf("IX");
input = input - 9;
} else {
printf("X");
input = input - 10;
}
} else if (input >= 4) {
/*
* V is 5 and IV is 4
* IV = V - I = 5 - 1 => 4
*/
if (input >= 5) {
printf("V");
input = input - 5;
} else {
printf("IV");
input = input - 4;
}
} else {
printf("I");
input = input - 1;
}
}
printf("\n");
}
int main () {
char data[10], ch;
int value = 0, power = 0, i = 0, j = 0;
/* get the octal input from the user */
printf("Enter your octal value:");
fgets(data, 10, stdin);
data[strlen(data) - 1] = '\0';
/* convert octal to decimal valueue */
for (i = strlen(data); i > 0; i--) {
ch = data[j++];
power = pow(8, i - 1);
if (ch >='0'&& ch <= '7') {
/* octal to decimal conversion */
value = value + (ch - '0') * power;
} else {
/* valueue other than 0-7 are invalueid */
printf("Wrong Input!!!\n");
return (-1);
}
}
decimalToRoman(value);
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Enter your octal value:754
Roman Number: CDXCII
Enter your octal value:754
Roman Number: CDXCII
No comments:
Post a Comment