有问题将数字转换为罗马数字

时间:2017-06-23 12:32:40

标签: c++ converter roman-numerals

对于类I我必须创建一个代码,以便它可以向用户询问1-99之间的整数,并能够以罗马数字打印该整数。问题是在创建我的代码之后,它只打印完全达到39的数字。一旦它达到40它就没有罗马数字输出,然后从41-99它不会打印第十位值(例如45将出现为V) 。这是我目前的代码。

    #include "stdafx.h"
#include <iostream>
#include <string>

using namespace std;

int main()
{
    int num;
    int tenum;
    int remnum;
    string romnum;
    string fromnum;

    cout << "Enter a number between 1 and 99. \n";
    cin >> num;

    tenum = num / 10;
    remnum = num % 10;

    if (tenum == 9)
    {
        fromnum == "XC";
    }
    else if (tenum == 8)
    {
        fromnum == "LXXX";
    }
    else if (tenum == 7)
    {
        fromnum == "LXX";
    }
    else if (tenum == 6)
    {
        fromnum == "LX";
    }
    else if (tenum == 5)
    {
        fromnum == "L";
    }
    else if (tenum == 4)
    {
        fromnum == "XL";
    }
    else if (tenum == 3)
    {
        fromnum = "XXX";
    }
    else if (tenum == 2)
    {
        fromnum == "XX";
    }
    else if (tenum == 1)
    {
        fromnum == "X";
    }

    if (remnum == 9)
    {
        romnum = "IX";
    }
    else if (remnum == 8)
    {
        romnum = "VIII";
    }
    else if (remnum == 7)
    {
        romnum = "VII";
    }
    else if (remnum == 6)
    {
        romnum = "VI";
    }
    else if (remnum == 5)
    {
        romnum = "V";
    }
    else if (remnum == 4)
    {
        romnum = "IV";
    }
    else if (remnum == 3)
    {
        romnum = "III";
    }
    else if (remnum == 2)
    {
        romnum = "II";
    }
    else if (remnum == 1)
    {
        romnum = "I";
    }



    cout << tenum << endl;
    cout << remnum << endl;
    cout << fromnum;
    cout << romnum << endl;

    return 0;


}

2 个答案:

答案 0 :(得分:2)

您混淆了===

更改

之类的行
fromnum == "XL"

fromnum = "XL"

Demo

(为简洁起见,我使用了switch语句)

答案 1 :(得分:0)

同样的回答:Converting integer to Roman Numeral

#include <iostream>
#include <string>

std::string to_roman(int value)
{
  struct romandata_t { int value; char const* numeral; };
  static romandata_t const 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 (romandata_t const* current = romandata; current->value > 0; ++current)
  {
    while (value >= current->value)
    {
      result += current->numeral;
      value  -= current->value;
    }
  }
  return result;
}

int main()
{
  for (int i = 1; i <= 4000; ++i)
  {
    std::cout << to_roman(i) << std::endl;
  }
}

此代码转换为1000.只需要你需要的东西就可以了! 来自http://rosettacode.org/wiki/Roman_numerals/Encode#C.2B.2B