I am attempting to create a program that will convert roman numerals to decimals and decimals to roman numerals. I have a code that works for the most part but, the answer it is achieving for the first and second test numeral are wrong. instead of coming up with the numbers 1114, 359 and 1666 it comes up with 11, 6 and 1666. Any help would be appreciated.
void romanType::convertToDecimal()
{
for (int i = 0; i < roman.size(); i++ ) //you could use roman.length() if you like
{
switch (roman[i]) //roman.at(i) is just a more secure way to do it
{
case'M': decimal += M; break;
case'D': decimal += D; break;
case'C': decimal += C; break;
case'L': decimal += L; break;
case'X': decimal += X; break;
case'V': decimal += V; break;
case'I':
if (roman[i + 1] != 'I' && i + 1 != roman.size())
decimal-=1;
else
decimal+=1;
break;
}
}
}
What you did was check if the first letter was M, the second letter D and so on, thats why the last number was correct.
void romanType::convertToDecimal()
{
for (int i = 0; i < roman.size(); i++ ) //you could use roman.length() if you like
{
switch (roman[i]) //roman.at(i) is just a more secure way to do it
{
case'M': decimal += M; break;
case'D':
if(i + 1 != roman.size() &&roman[i+1] == 'M')
decimal -= D;
else
decimal += D; break;
case'C':
if(i + 1 != roman.size() && roman[i+1] == 'M' || roman[i+1] == 'D')
decimal -= C;
else
decimal += C; break;
case'L': decimal += L; break;
etc...
case'X': decimal += X; break;
etc...
case'V': decimal += V; break;
etc...
case'I':
if ( i + 1 != roman.size() && roman[i + 1] != 'I')
decimal-=1;
else
decimal+=1;
break;
}
}
}
which looks (to me at last) more intuitive as you just check if next digital is greater than current one and if so it's detracted instead of added to the Roman number.
Also I changed the order of boundary check since C++ used short-circuited calculation.