I have a test due in about four hours and one of the questions asks us to convert a user-inputed integer up to 100 into a roman numeral. I think my code is very close (I fou
Function to Convert Decimal to Roman Numrals string toLongRoman(int x) {
string Romanvalue;
string Roman[13] = { "M","CM","D","CD", "C","XC", "L","XL", "X","IX","V","IV", "I" };
int Numbers[13] = { 1000, 900, 500,400, 100,90,50,40,10,9,5,4,1 };
for (int index = 0; index < 13; index++) {
while (x >= Numbers[index]) {
Romanvalue += Roman[index];
x -= Numbers[index];
}
}
return Romanvalue;
Joachim found the first problem, this code is always executed and overwrite input with 100.
if(input = 100)
{
romnum + 'C';
}
Now, why don't you see anything? That's because you miss another =
. All other code correctly uses +=
but this uses +
. As a result, this doesn't assign the resulting string back to romnum
.
BTW, since romnum
is still empty, you can use romnum = 'C'
or romnum += 'C'
interchangeably.
From http://rosettacode.org/wiki/Roman_numerals/Encode#C.2B.2B
std::string to_roman(unsigned int value)
{
struct romandata_t { unsigned int value; char const* numeral; };
const struct romandata_t romandata[] =
{
{1000, "M"}, {900, "CM"},
{500, "D"}, {400, "CD"},
{100, "C"}, { 90, "XC"},
{ 50, "L"}, { 40, "XL"},
{ 10, "X"}, { 9, "IX"},
{ 5, "V"}, { 4, "IV"},
{ 1, "I"},
{ 0, NULL} // end marker
};
std::string result;
for (const romandata_t* current = romandata; current->value > 0; ++current)
{
while (value >= current->value)
{
result += current->numeral;
value -= current->value;
}
}
return result;
}