将整数转换为罗马数字
问题描述:
我要在大约四个小时内进行一次测试,其中一个问题要求我们将用户输入的最大100的整数转换为罗马数字。我认为我的代码非常接近(我找到了我用作指导的youtube视频),但是可惜我的代码根本行不通:(。有人可以发现错误吗?编辑:啊,很抱歉,问题是
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 found a youtube video that I sort of used as a guide) but alas my code simply will not work :(. Can anyone spot the errors? Ah sry sry sry, the problem is that when it compiles, it gives no Roman numerals. As in I enter a value and it gives me a blank.
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
string romnum;
int input;
int num;
cout << "Type in an integer: ";
cin >> input;
if(( input >= 101) || (input <= 0)) // <-- this is the upper bound
{
cout << "\n INVALID INPUT";
}
else
{
if(input = 100)
{
romnum + 'C';
}
input %= 100; // gets the remainder after dividing by 100
if(input <= 10)
{
num = (input/10); // now we are dealing with number in 10s place
if(num == 9)
{
romnum += "XC";
}
else if(num >= 5)
{
romnum += 'L';
for(int i=0; i < num - 5;i++)
{
romnum += 'X';
}
}
else if(num == 4)
{
romnum += "XL";
}
else if(num >= 1)
{
for(int i=0; i>num; i++)
{
romnum += 'X';
}
input %= 10;
}
if(num >= 1)
{
num = input; // now we are dealing with number in ones place
if(num == 9)
{
romnum += "IX";
}
else if(num >= 5)
{
romnum += 'V';
for(int i=0; i < num - 5; i++)
{
romnum += 'I';
}
}
else if(num == 4)
{
romnum += "IV";
}
else if(num >= 1)
{
for(int i = 0; i < num; i++)
{
romnum += 'I';
}
}
cout << "The Roman Numeral is: " << romnum;
}
}
cout << "The Roman Numeral is: " << romnum;
}
int f;
cin >> f;
return 0;
}
enter code here
答
来自 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;
}