蓝桥杯——第八周校内练习总结(罗马数字与十进制数互转)

先给出罗马数字与十进制对应的表:

I     V    X      L      C         D          M

1    5    10    50    100     500     1000

特别的,要首先考虑这几个:

IV 是4,4不是IIII;同理9是IX;40是XL;90XC;400CD;900CM。

所以先给出十进制int转罗马数字的代码:

int num[7] = { 1, 5,10,50,100,500,1000 };
char str[7] = { 'I','V','X','L','C','D','M' };
void changeTwo(int x)
{
	int q, b, g;
	q = x / 1000;
	for (int i = 0; i < q; i++)
		cout << 'M';
	x = x % 1000;
	if (x >= 900)
	{
		cout << "CM";
		x = x - 900;
	}
	else if (x >= 500)
	{
		cout << 'D';
		x = x - 500;
	}
	else if (x >= 400)
	{
		cout << "CD";
		x = x - 400;
	}
	b = x / 100;
	x = x % 100;
	for (int i = 0; i < b; i++)
		cout << 'C';
	if (x >= 90)
	{
		cout << "XC";
		x = x - 90;
	}
	else if (x >= 50)
	{
		cout << 'L';
		x = x - 50;
	}
	else if (x >= 40)
	{
		cout << "XL";
		x = x - 40;
	}
	g = x / 10;
	x = x % 10;
	for (int i = 0; i < g; i++)
		cout << 'X';
	if (x >= 9)
	{
		cout << "IX";
		x = x - 9;
	}
	else if (x >= 5)
	{
		cout << 'V';
		x = x - 5;
	}
	else if (x == 4)
	{
		cout << "IV";
		x = x - 4;
	}
	for (int i = 0; i < x; i++)
		cout << 'I';
	cout << endl;
}

接着是罗马数字转十进制的算法,这个比十进制转罗马要复杂,需要更加注意:

传入一个string类型的pL返回一个相对应的int值。

int num[7] = { 1, 5,10,50,100,500,1000 };
char str[7] = { 'I','V','X','L','C','D','M' };
int change(string pL)
{
	int c = 0;
	int j, k;
	int a[100];
	int sum = 0;
	for (j = 0; j<100; j++)
	{
		a[j] = -1;
	}
	for (j = 0; pL[j] != '\0'; j++)
	{
		for (k = 0; k<100; k++)
		{
			if (pL[j] == str[k])
			{
				a[j] = num[k];
				break;
			}
		}
	}
	for (j = 0; j<100; j++)
	{
		if (a[j] == -1)
			break;
		if (a[j]<a[j + 1])
		{
			sum += a[j + 1] - a[j];
			j++;
			continue;
		}
		else
			sum += a[j];
	}
	return sum;
}

猜你喜欢

转载自blog.csdn.net/qq_41938259/article/details/84390882