在C ++中将罗马数字转换为介于1到3999之间的十进制
在本教程中,我们将讨论将罗马数字转换为介于1到3999之间的十进制的程序。
为此,我们将获得一个随机的罗马数字。我们的任务是将给定的罗马数字转换为其十进制等效形式。
示例
#include<bits/stdc++.h>
using namespace std;
//calculating the decimal value
int value(char r){
if (r == 'I')
return 1;
if (r == 'V')
return 5;
if (r == 'X')
return 10;
if (r == 'L')
return 50;
if (r == 'C')
return 100;
if (r == 'D')
return 500;
if (r == 'M')
return 1000;
return -1;
}
//calculating decimal equivalent of given numeral
int convert_decimal(string &str){
int res = 0;
for (int i=0; i<str.length(); i++){
//getting value of digit
int s1 = value(str[i]);
if (i+1 < str.length()){
int s2 = value(str[i+1]);
if (s1 >= s2){
res = res + s1;
}
else{
res = res + s2 - s1;
i++;
}
}
else{
res = res + s1;
}
}
return res;
}
int main(){
string str ="MCMIV";
cout << "Integer form:"
<< convert_decimal(str) << endl;
return 0;
}输出结果
Integer form:1904
热门推荐
10 对患者生日祝福语简短
11 结婚祝福语简短装备
12 周岁祝福语学生文案简短
13 订婚领证祝福语简短精辟
14 导师获奖祝福语大全简短
15 新婚购房祝福语简短精辟
16 牛年祝福语简短的爱人
17 送芒果的祝福语简短
18 送给学长毕业祝福语简短