Roman numbers. Write a program that converts a positive integer into the Roman n
ID: 3623972 • Letter: R
Question
Roman numbers. Write a program that converts a positive integer into the Roman number system. The Roman number system has digitsI=1
V=5
X=10
L=50
C=100
D=500
M=1,000
Numbers are formed according to the following rules. (1) Only numbers up to 3,999 are represented. (2) As in the decimal system, the thousands, hundred, tens, and ones are expressed separately. (3) The numbers 1 to 9 are expressed as
I=1
II=2
III=3
IV=4
V=5
VI=6
VII=7
VIII=8
IX=9
As you can see, a I preceding a V or X is subtracted from the value, and you can never have more than three I's in a row. (4) Tens and hundreds are done the same way, except that the letters X, L, C and C, D, M are used instead of I, V, X, respectively.
Your program should take an input, such as 1978, and convert it to Roman numerals, MCMLXXVIII.
Explanation / Answer
please rate - thanks
#include <iostream>
#include <string.h>
using namespace std;
int pow(int n)
{int i,val=1;
for(i=1;i<=n;i++)
val*=10;
return val;
}
int main()
{
string num;
int inum[4],digits,i,place,j,inval,number;
char value[20]="";
do
{
cout<<"enter a number between 1 and 3999 ";
cin>>num;
number=0;
digits=0;
while(num[digits]!='')
{inum[digits]=num[digits]-48;
digits++;
}
j=1;
for(i=digits-1;i>=0;i--)
{
number=number+inum[i]*j;
j*=10;
}
}while(number<1||number>3999);
place=pow(digits-1);
inval=0;
for(i=0;i<digits;i++)
{
switch(place)
{case 1000:
for(j=0;j<inum[i];j++)
value[inval++]='M';
break;
case 100:
switch(inum[i])
{case 9:strcat(value,"CM");
inval+=2;
break;
case 4:strcat(value,"CD");
inval+=2;
break;
case 8:case 7: case 6: case 5:
strcat(value,"D");
inval++;
for(j=0;j<inum[i]-5;j++)
value[inval++]='C';
break;
case 1: case 2: case 3:
for(j=0;j<inum[i];j++)
value[inval++]='C';
break;
}
break;
case 10:switch(inum[i])
{case 9:strcat(value,"XC");
inval+=2;
break;
case 4:strcat(value,"XL");
inval+=2;
break;
case 8:case 7: case 6: case 5:
strcat(value,"L");
inval++;
for(j=0;j<inum[i]-5;j++)
{strcat(value,"X");
inval++;
}
break;
case 1: case 2: case 3:
for(j=0;j<inum[i];j++)
{strcat(value,"X");
inval++;
}
break;
}
break;
case 1:switch(inum[i])
{case 9:strcat(value,"IX");
inval+=2;
break;
case 4:strcat(value,"IV");
inval+=2;
break;
case 8:case 7: case 6: case 5:
strcat(value,"V");
inval++;
for(j=0;j<inum[i]-5;j++)
{strcat(value,"I");
inval++;
}
break;
case 1: case 2: case 3:
for(j=0;j<inum[i];j++)
{strcat(value,"I");
inval++;
}
break;
}
}
place/=10;
}
value[inval]='';
cout<<number<<" in Roman Numerals is "<<value<<endl;
system("pause");
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.