Roman Numeral Converter - C++ Write a program to read in Old Roman numerals and
ID: 668313 • Letter: R
Question
Roman Numeral Converter - C++
Write a program to read in Old Roman numerals and print out their value (base 10 numbers). Old Roman numerals do not have a smaller value in front of a larger one.
**Cannot use arrays,classes, or length() as we have not covered them yet. Must use a while loop, and a switch. Use the enter key as the escape from the loop. (Empty line enter key to escape). Display must show what was entered plus the results.**
Example input: Result:
III III = 3
V V = 5
XVIII XVIII = 18
MCCXXVI MCCXXVI = 1226
I is 1
V is 5
X is 10
L is 50
C is 100
D is 500
M is 1000
Explanation / Answer
#include <iostream>
#include <string>
using namespace std;
int main()
{
string romanNum = "I";
char ch = "I";
cout << "Welcome to the Roman Numeral Converter."<<endl;
while(romanNum != "")
{
cout << "Enter the roman numberal to convert";
cin >> romanNum;
int length = romanNum.size();
int i = 0,sum =0,previous = 1000;
while( i<length )
{
switch(romanNum.at(i))
{
case 'M':
sum += 1000;
if(previous < 1000)
{
sum -= 2 * previous;
}
previous = 1000;
break;
case 'D':
sum += 500;
if(previous < 500)
{
sum -= 2 * previous;
}
previous = 500;
break;
case 'C':
sum += 100;
if(previous < 100)
{
sum -= 2 * previous;
}
previous = 100;
break;
case 'L':
sum += 50;
if(previous < 50)
{
sum -= 2 * previous;
}
previous = 50;
break;
case 'X':
sum += 10;
if(previous < 10)
{
sum -= 2 * previous;
}
previous = 10;
break;
case 'V':
sum += 5;
if(previous < 5)
{
sum -= 2 * previous;
}
previous = 5;
break;
case 'I':
sum += 1;
if(previous < 1)
{
sum -= 2 * previous;
}
previous = 1;
break;
}
i++;
}
cout << romanNum << " : " <<sum<<endl;
}
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.