罗马到整数在 C++ 中使用 STL
Roman to Integer using STL in C++
我是 STL 的新手,我试图使用映射和向量将罗马数字转换为相应的整数。但是,我的输出变化很大并且不准确。 "X" 的实例输出为 20,但 "XI" 的输出为 12。我将字符串作为输入,然后将其拆分转换成字符并将它们存储在向量中。然后将该向量传递给函数,该函数基本上将罗马人计算为整数。
这是我尝试过的:-
#include<algorithm>
#include<string>
#include<bits/stdc++.h>
using namespace std;
void roman_int(vector<char> &s){
map<char,int> roman;
roman['M'] = 1000;
roman['D'] = 500;
roman['C'] = 100;
roman['L'] = 50;
roman['X'] = 10;
roman['V'] = 5;
roman['I'] = 1;
int res=0;
for(int i=0;i<s.size();++i){
if(roman[s[i]]<roman[s[i+1]]){
res -= roman[s[i]];
}
else{
res += roman[s[i]];
}
}
res += roman[s[s.size()-1]];
cout<<res;
}
int main(){
string numeral;
cin>>numeral;
vector<char> s(numeral.begin(), numeral.end()); //Splitting the string to characters
roman_int(s);
}
您的 for 循环似乎 运行 超出了需要。
int res=0;
for(int i=0;i<s.size();++i){
if(roman[s[i]]<roman[s[i+1]]){
res -= roman[s[i]];
}
else{
res += roman[s[i]];
}
}
res += roman[s[s.size()-1]];
cout<<res;
for 循环末尾有另一次迭代,导致最后一个元素被添加两次。要修复它,请删除最后一次迭代 res += roman[s[s.size()-1]];
或从 for 循环的条件 for(int i=0;i<s.size()-1;++i)
.
中减去 1
我是 STL 的新手,我试图使用映射和向量将罗马数字转换为相应的整数。但是,我的输出变化很大并且不准确。 "X" 的实例输出为 20,但 "XI" 的输出为 12。我将字符串作为输入,然后将其拆分转换成字符并将它们存储在向量中。然后将该向量传递给函数,该函数基本上将罗马人计算为整数。 这是我尝试过的:-
#include<algorithm>
#include<string>
#include<bits/stdc++.h>
using namespace std;
void roman_int(vector<char> &s){
map<char,int> roman;
roman['M'] = 1000;
roman['D'] = 500;
roman['C'] = 100;
roman['L'] = 50;
roman['X'] = 10;
roman['V'] = 5;
roman['I'] = 1;
int res=0;
for(int i=0;i<s.size();++i){
if(roman[s[i]]<roman[s[i+1]]){
res -= roman[s[i]];
}
else{
res += roman[s[i]];
}
}
res += roman[s[s.size()-1]];
cout<<res;
}
int main(){
string numeral;
cin>>numeral;
vector<char> s(numeral.begin(), numeral.end()); //Splitting the string to characters
roman_int(s);
}
您的 for 循环似乎 运行 超出了需要。
int res=0;
for(int i=0;i<s.size();++i){
if(roman[s[i]]<roman[s[i+1]]){
res -= roman[s[i]];
}
else{
res += roman[s[i]];
}
}
res += roman[s[s.size()-1]];
cout<<res;
for 循环末尾有另一次迭代,导致最后一个元素被添加两次。要修复它,请删除最后一次迭代 res += roman[s[s.size()-1]];
或从 for 循环的条件 for(int i=0;i<s.size()-1;++i)
.