Please check the below link to know about how to write roman numerals.
Write a C program to convert roman numeral to its decimal equivalent.
#include <string.h>
#include <stdlib.h>
/* converts given value to its binary equivalent */
int romToDeci(char ch) {
int ret;
switch (ch) {
case 'I':
ret = 1;
break;
case 'V':
ret = 5;
break;
case 'X':
ret = 10;
break;
case 'L':
ret = 50;
break;
case 'C':
ret = 100;
break;
case 'D':
ret = 500;
break;
case 'M':
ret = 1000;
break;
default:
printf("Wrong Input!!\n");
exit(0);
}
return ret;
}
int main() {
char data[100];
int value, i, j, len;
/* get the roman numeral from the user */
printf("Enter your Roman Numeral:");
fgets(data, 100, stdin);
data[strlen(data) - 1] = '\0';
len = strlen(data);
/* roman to decimal conversion */
value = romToDeci(data[len - 1]);
for (i = len - 1; i > 0; i--) {
/*
* For roman numeral like IV, XL etc, the previous
* digit will be lesser than the current digit. So,
* we can find their decimal equivalent as follows.
* IV => V - I => 5 - 1 => 4
* XL => L - X => 50 - 10 => 40
*/
if (romToDeci(data[i]) > romToDeci(data[i - 1])) {
value = value - romToDeci(data[i - 1]);
} else {
value = value + romToDeci(data[i - 1]);
}
}
printf("Decimal Value: %d\n", value);
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Enter your Roman Numeral:XCIX
Decimal Value: 99
Enter your Roman Numeral:XCIX
Decimal Value: 99
cool work...
ReplyDelete/*this program converts roman number to decimal number*/
ReplyDelete#include
#include
int main()
{
int i,lf,rt,j,s=0,flag=0,N[7]={1,5,10,50,100,500,1000};
char R[7]={'I','V','X','L','C','D','M'},*S;
S=malloc(256);
printf("\nEnter Roman Numerical's: ");
scanf("%s",S);
printf("\nEntered Roman Numerical :%s ",S);
for(j=0;S[j];j++)
{
for(i=0;i<7;i++)
{
if(R[i]==S[j])
{
lf=i;
break;
}
}
for(i=0;i<7,S[j+1]!='\0';i++)
{
if(R[i]==S[j+1])
{
rt=i;
break;
}
}
if((S[j]=='V'))
++flag;
if(((N[lf]>N[rt])||(lf==rt)||(rt==-1))&&(flag<2))
{
s+=N[lf];
}
else if((N[lf]<N[rt])&&(rt<3)&&(S[j+2]=='\0'))
{
s+=N[rt]-N[lf];
j++;
}
else
{
printf("\n\nEnter Valid Roman Numerical Number\n");
return 1;
}
rt=lf=-1;
}
printf("\nRoman's Equivalent Number : %d\n",s);
return 0;
}