在C++中使用find语句将罗马数字转换为数字
Converting roman numerals into numbers using find statement in C++
嗨,我在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) {
我不为您做调试,我只确定三个问题。
-
您正在
romanNum
中搜索,但正在擦除从input
中找到的字符。那不应该是同一根绳子吗? -
您得到15,因为在数字中找到的第一个
unit
字符串是"V"
,而不是"IV"
,因为您正在按相反的顺序迭代。 -
你不应该寻找是你的号码前缀的字符串吗?没有任何内容。您希望
find
方法返回0,而不是其他任何内容。
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 检查输入是否不是整数或数字
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- 如何用数字处理log(0)
- 最高有效数字侧的第N位
- 如何获取一个数字的前3位
- 查找最接近的大于当前数字的数字的索引
- 找到两对数字,使它们的乘积的绝对差最小化
- 我想做一个彼此不同但重复出现的数字
- 将数字转换为字母(例如:123 转换为一二三)
- C++如何计算用户输入的数字中的偶数位数
- 如何在C++中确定文本文件中的元素是字符还是数字
- 打印数字图案
- C++问题:用户认为数字1-100,程序提出问题不超过6次即可得到答案。无法正确
- 如何检查一个c++字符串中有多少相同的字符/数字
- 求出有多少个数字是完美平方,而sqrt()是L,R范围内的素数
- 将数字打印成文字
- 当使用比格式支持的精度更高的精度来显示数字时,会写出什么数据
- 在将数字随机生成为数组期间从内存输出随机数的数组