# C++プログラミング：アラビア数字をローマ数字に変換する

Arabic numberをRoman numeralにconvertするには、ローマ数字のⅤやⅩ等の数字を下記のようにアラビア数字に対応させる必要がある。

1000,900,500,400,100,90,50,40,10,9,5,4,1
"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"

 1234 vector> introm = {     {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"}   };

 1234567891011 #include #include //vectorを使うのに必要 using namespace std; string introm(int a) {　//整数/ローマ数字変換関数introm   vector> intstr = {     {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"}   };

vectorを使いたくない場合はarrayを使って以下のように書ける。

 1234567 #include using namespace std; string introm(int a){ int intnum[] = {1000,900,500,400,100,90,50,40,10,9,5,4,1}; const char *romnum[] = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};

 12345678910111213141516171819202122232425262728 #include using namespace std; string introm(int a) {   int intnum[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};   const char *romnum[] = {"M",  "CM", "D",  "CD", "C",  "XC", "L",                           "XL", "X",  "IX", "V",  "IV", "I"};   string s;   int i = 0;   while (a) {     while (a / intnum[i]) {       s += romnum[i];       a -= intnum[i];     }     i++;   }   return s; } int main() {   int a;   cout << "Enter an integer number:\n";   cin >> a;   cout << a << " is " << introm(a) << '\n';   return 0; }

このコードを実行するC++ shell

スポンサーリンク

フォローする