Here is a C++ program to convert decimal number to Roman and vice versa.
C++ program to convert decimal to Roman
#include<iostream>
using namespace std;
int main()
{
int number;
cout<<"Enter number ";
cin>>number;
while(number>0)
{
if(number>=1000)
{
cout<<"M";
number-=1000;
}
else if(number>=900)
{
cout<<"CM";
number-=900;
}
else if(number>=500)
{
cout<<"D";
number-=500;
}
else if(number>=400)
{
cout<<"CD";
number-=400;
}
else if(number>=100)
{
cout<<"C";
number-=100;
}
else if(number>=90)
{
cout<<"XC";
number-=90;
}
else if(number>=50)
{
cout<<"L";
number-=50;
}
else if(number>=40)
{
cout<<"XL";
number-=40;
}
else if(number>=10)
{
cout<<"X";
number-=10;
}
else if(number>=9)
{
cout<<"IX";
number-=9;
}
else if(number>=5)
{
cout<<"V";
number-=5;
}
else if(number>=4)
{
cout<<"IV";
number-=4;
}
else if(number>=1)
{
cout<<"I";
number-=1;
}
}
return 0;
}
using namespace std;
int main()
{
int number;
cout<<"Enter number ";
cin>>number;
while(number>0)
{
if(number>=1000)
{
cout<<"M";
number-=1000;
}
else if(number>=900)
{
cout<<"CM";
number-=900;
}
else if(number>=500)
{
cout<<"D";
number-=500;
}
else if(number>=400)
{
cout<<"CD";
number-=400;
}
else if(number>=100)
{
cout<<"C";
number-=100;
}
else if(number>=90)
{
cout<<"XC";
number-=90;
}
else if(number>=50)
{
cout<<"L";
number-=50;
}
else if(number>=40)
{
cout<<"XL";
number-=40;
}
else if(number>=10)
{
cout<<"X";
number-=10;
}
else if(number>=9)
{
cout<<"IX";
number-=9;
}
else if(number>=5)
{
cout<<"V";
number-=5;
}
else if(number>=4)
{
cout<<"IV";
number-=4;
}
else if(number>=1)
{
cout<<"I";
number-=1;
}
}
return 0;
}
C++ program to convert Roman to decimal
#include<iostream>
#include<math.h>
#include<stdio.h>
using namespace std;
int deci(char c)
{
switch(c)
{
case 'M':
case 'm':
return 1000;
case 'D':
case 'd':
return 500;
case 'C':
case 'c':
return 100;
case 'L':
case 'l':
return 50;
case 'X':
case 'x':
return 10;
case 'V':
case 'v':
return 5;
case 'I':
case 'i':
return 1;
}
}
int main()
{
char rom[20];
int i=0,decimal=0;
cout<<"Enter roman number ";
gets(rom);
while(rom[i]!='\0')
{
if(deci(rom[i])<deci(rom[i+1]))
{
decimal+=deci(rom[i+1])-deci(rom[i]);
i+=2;
}
else
{
decimal+=deci(rom[i]);
i++;
}
}
cout<<"Decimal Equivalent "<<decimal;
}
#include<math.h>
#include<stdio.h>
using namespace std;
int deci(char c)
{
switch(c)
{
case 'M':
case 'm':
return 1000;
case 'D':
case 'd':
return 500;
case 'C':
case 'c':
return 100;
case 'L':
case 'l':
return 50;
case 'X':
case 'x':
return 10;
case 'V':
case 'v':
return 5;
case 'I':
case 'i':
return 1;
}
}
int main()
{
char rom[20];
int i=0,decimal=0;
cout<<"Enter roman number ";
gets(rom);
while(rom[i]!='\0')
{
if(deci(rom[i])<deci(rom[i+1]))
{
decimal+=deci(rom[i+1])-deci(rom[i]);
i+=2;
}
else
{
decimal+=deci(rom[i]);
i++;
}
}
cout<<"Decimal Equivalent "<<decimal;
}
No comments:
Post a Comment