0

嗨,我无法在 C++ 中将罗马数字转换为普通数字,代码在一定程度上可以工作,但是如果输入数字(XIV 14 或 LIV 等),它将输出 15 或 55。我试图实现 find 语句但是我不知道如何使用它来解决我的问题,这是我的代码的副本;

int convNum;
int total = 0;
string romanNum;
const string units [10]= {"0","I","II","III","IV","V","VI","VII","VIII","IX"};
const string tens [10]= {"0","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"};
const string hundreds [10]= {"0","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"};
const string thousands [4]= {"0","M","MM","MMM"};
string input;

while(!cin.eof()){
    cin>>romanNum;
    if(cin.fail()){
        break;
    }else{
        for(int i=0; i<romanNum.length(); i++){
            romanNum[i]=toupper(romanNum[i]);
        }
        for(int y=3; y > 0; y--){
           if(romanNum.find(thousands[y])!= string::npos){
               total += y*1000;
               input.erase(0,thousands[y].length());
               break;
            }
        }
        for(int y=9; y > 0; y--){
           if(romanNum.find(hundreds[y])!= string::npos){
               total += y*100;
               input.erase(0,hundreds[y].length());
               break;
            }
        }
        for(int y=9; y > 0; y--){
           if(romanNum.find(tens[y])!= string::npos){
               total += y*10;
               input.erase(0,tens[y].length());
               break;
            } 
        }
        for(int y=9; y > 0; y--){
           if(romanNum.find(units[y])!= string::npos){
               total += y;
               input.erase(0,units[y].length());
               break;
            }
        }
        cout << total << endl;
        total = 0;
           }

        for(int k=0; k < romanNum.length(); k++){
            input[k] = romanNum[k];
        }


        }     


return 0;

}

如果有人可以帮助我,我将不胜感激,因为我是初学者,编写这么多的 C++ 代码花了我大约 2 周的时间来编写代码。

4

2 回答 2

1

看起来你有两个问题:

首先,当您擦除找到的数字时,您是从input字符串中擦除,而不是从字符串中擦除romanNum。您应该从romanNum字符串中删除:

romanNum.erase(0, thousands[y].length());

其次,看起来您正在字符串中的任何位置搜索结果,而不仅仅是在开头。所以在“LIV”的例子中,当你在units列表中搜索时,它会在列表的末尾找到“V”,加上5,然后它会擦除“I”(因为它总是从前面擦除)列表。对此的一种解决方案是只接受当前字符串开头的结果。所以,不要做!= string::npos,只需做== 0

if (romanNum.find(thousands[y]) == 0) {
于 2013-08-31T15:12:52.090 回答
0

我不会为你做调试,我只会找出三个问题。

  1. 您正在搜索,romanNum但您正在删除从中找到的字符input。那不应该是同一个字符串吗?

  2. 您得到 15 是因为unit在数字中找到的第一个字符串是"V",而不是"IV",因为您以相反的顺序进行迭代。

  3. 您不应该寻找作为您号码前缀的字符串吗?不在它的任何地方。您希望该find方法返回 0,而不是其他任何值。

于 2013-08-31T15:13:01.900 回答