罗马数字转换整数_C ++程序将罗马数字转换为整数

该博客介绍了一个C++程序,用于将给定的罗马数字转换为对应的整数值。通过提供示例和算法说明,阐述了如何将罗马数字如IV、IX等转换成十进制数字。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

罗马数字转换整数

Given a number in Roman format and we have to convert it into integer/decimal format.

给定罗马格式的数字,我们必须将其转换为整数/十进制格式。

Example:

例:

    Input: XIV
    Output: 14

    Input: XI
    Output: 11

Algorithm:

算法:

roman_to_int(string roman)

roman_to_int(罗马字符串)

Step 1: Declare all Roman characters and its integer value 
        in a Array ( rmap[] ) where Index=’Roman_character’
Step 2: If (Length of roman) =<1
            Return corresponding Array index value.
Step 3: else
Step 4: Repeat step 5 and step 6, While((i<roman.size()) 
Step 5: if(rmap[roman[i]]<rmap[roman[i+1]])
            number+=rmap[roman[i+1]]-rmap[roman[i]]		
            //number is storing the integer number 
            //after conversion; number=0
            i+=2;
Step 6: else
        number+=rmap[roman[i]]
        i++
Step 7:
return number

Program:

程序:

#include <bits/stdc++.h>
using namespace std;

int roman_to_int(string roman){
	map<char,int> rmap;
	rmap['I'] =   1;
	rmap['V'] =   5;
	rmap['X'] =  10;
	rmap['L'] =  50;
	rmap['C'] = 100;
	rmap['D'] = 500;
	rmap['M'] =1000;
	int number=0,i=0;
	
	//If input is only one character
	if(roman.length()<=1){
		return rmap[roman.at(0)];
	}
	else{
		while(i<roman.size()){
			if(rmap[roman[i]]<rmap[roman[i+1]]){
				number+=rmap[roman[i+1]]-rmap[roman[i]];
				i+=2;
			}
			else{
				number+=rmap[roman[i]];
				i++;
			}
		}
		return number;
	}
}

int main(){
	string roman;
	
	cout<<"Enter the roman number (in capital only): ";
	getline(cin,roman);
	
	int number;
	number=roman_to_int(roman);
	
	cout<<"The interger form is: "<<number;
	
	return 0;
}


Output

输出量

Enter the roman number (in capital only): XIV
The interger form is: 14

Explanation:

说明:

Sample Input : XIV
=>  String lenght is >1, so it is "else" part of roman_to_int() 
will execute here.
Step1:  
i=0, so, 0<3 (size of string), while loop will execute.
Now, rmap[roman[0]]=rmap[X] that is equal to 10, and 
rmap[roman[1]]=1,
So, 10<1 that is false, so "else" part inside the while loop 
will execute and 
number+=rmap[roman[i]];
=> number=0+10
=>number=10 and i=0+1 that is i=1
Step2:
i=1, so, 1<3, again while loop will execute.
Now, rmap[roman[1]]=rmap[I] that is eaual to 1 and 
rmap[roman[2]]=5,
So, 1<5, that is true... So, if part inside the while loop will 
execute and
number+=rmap[roman[i+1]]-rmap[roman[i]];
=>number+=rmap[V]-rmap[I]
=>number+=5-1
=>number+=4
=>number=10+4
=>number=14
And, i=i+2 that is i=3
Step3:
i=3, so, 3<3 that is false.

So, return value will be 14.


翻译自: https://www.includehelp.com/cpp-programs/convert-roman-number-to-integer-number.aspx

罗马数字转换整数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值