C++罗马数字与十进制数字互相转换

//罗马数字转十进制
 int map(char a)
{
	switch (a)
	{
	case 'I':
		return 1;
	case 'V':
		return 5;
	case 'X':
		return 10;
	case 'L':
		return 50;
	case 'C':
		return 100;
	case 'D':
		return 500;
	case 'M':
		return 1000;
	default:
		break;
	}
	return 0;
}

 
  
int RomanToInt(string s)
 {
	 int result = 0;//返回结果  
					//比较当前字符与前一个字符,如果较小,则直接加上对应的数,如果较大,则加上对应的数并且减去2倍的前一个数  
	 for (size_t i = 0; i < s.size(); i++)
	 {
		 if (i>0 && map(s[i]) > map(s[i - 1]))
			 result += map(s[i]) - 2 * map(s[i - 1]);
		 else
			 result += map(s[i]);
	 }
	 return result;
 }
 
  
//十进制转罗马数字
string IntTorRoma(int num)
{
char* chac[4][10] = {  
		{ "","I","II","III","IV","V","VI","VII","VIII","IX" },
		{ "","X","XX","XXX","XL","L","LX","LXX","LXXX","XC" },
		{ "","C","CC","CCC","CD","D","DC","DCC","DCCC","CM" },
		{ "","M","MM","MMM" } };

	int num;
	cin >> num; 
	string roam;
	roam.append(chac[3][num / 1000  % 10]);
	roam.append(chac[2][num / 100 % 10]);
	roam.append(chac[1][num / 10 % 10]);
	roam.append(chac[0][num % 10]);
	return roam;
}
 
  
 
  
 
 

你可能感兴趣的:(C++)