gpt4 book ai didi

c++ - 在 C++ 中使用 find 语句将罗马数字转换为数字

转载 作者:行者123 更新时间:2023-11-28 07:27:15 24 4
gpt4 key购买 nike

您好,我在将罗马数字转换为 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 周的时间。

最佳答案

看起来你有两个问题:

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

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

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

if (romanNum.find(thousands[y]) == 0) {

关于c++ - 在 C++ 中使用 find 语句将罗马数字转换为数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18549453/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com