將介於 1 到 3999 之間的羅馬數字轉換為十進位制的 C++ 程式碼
在本教程中,我們將討論一個程式,將介於 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
廣告
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP