Write a program that converts a Roman number such as MCMLXXVIII to its decimal n
ID: 674883 • Letter: W
Question
Write a program that converts a Roman number such as MCMLXXVIII to its decimal number representation that uses the following functions:
int romanCharValue(char r): yields the numeric value of the passed Roman numeral character.
int convertRomanToInt(string s): this function converts the Roman number string into its equivalent integer value by implementing the following algorithm.
total = 0
While the roman number string is not empty
If the first character has a larger or equal value than the second, or the string has length 1
Add value(first character) to total.
Remove the character.
Else
Add the quantity: value(second character) - value(first character) to total.
Remove both characters.
Provide a program that tests your functions via a loop construct for acquiring testing data.
Example run (with user input indicated with bold italics):
Enter Roman number or Q to quit: I
I = 1
Enter Roman number or Q to quit: V
V = 5
Enter Roman number or Q to quit: X
X = 10
Enter Roman number or Q to quit: L
L = 50
Enter Roman number or Q to quit: C
C = 100
Enter Roman number or Q to quit: D
D = 500
Enter Roman number or Q to quit: M
M = 1000
Enter Roman number or Q to quit: MCMLXII
MCMLXII = 1962
Enter Roman number or Q to quit: MDCCCLXXXVIII
MDCCCLXXXVIII = 1888
Enter Roman number or Q to quit: Q
Explanation / Answer
#include <iostream>
#include <string>
using namespace std;
int romanCharValue(char r)
{
if(r == 'M')
return 1000;
else if(r == 'D')
return 500;
else if(r == 'C')
return 100;
else if(r == 'L')
return 50;
else if(r == 'X')
return 10;
else if(r == 'V')
return 5;
else if(r == 'I')
return 1;
return 0;
}
int convertRomanToInt(string s)
{
int i, total = 0;
char c, cnext;
for (i=0; i<(s.length()-1); ++i)
{
c= s.at(i);
cnext = s.at(i + 1);
if(romanCharValue(c) >= romanCharValue(cnext))
{
total += romanCharValue(c);
}
else
{
total += (romanCharValue(cnext) - romanCharValue(c));
i++;
}
}
total += romanCharValue(s.at(i));
return total;
}
int main()
{
string roman;
while(1)
{
cout<<"Enter Roman number or Q to quit: ";
cin>>roman;
if(roman.at(0) == 'Q')
exit(0);
cout<<roman<<" = "<<convertRomanToInt(roman)<<endl;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.