罗马数制__十进制数与罗马数的转换__数字分离

一、罗马数制

罗马数没有权和基数。

Ⅰ Ⅱ Ⅲ Ⅳ Ⅴ Ⅵ Ⅶ Ⅷ Ⅸ Ⅹ Ⅺ Ⅻ     L       C          D            M

1                5                   10            50     100      500        1000

相同的数并列,表示相加:ⅩⅩ = 10 + 10 = 20

右边 < 左边 , 表示相加 : Ⅷ = 5+1+1+1 = 8

左边 < 右边 , 表示右数减左数:Ⅸ = 10 -1 = 9

数字上面加一横,表示原数的1000倍: 非X = 10000

XXIV = 10+ 10 + ( 5-1) = 24


二、阿拉伯数字表示的正整数 转换为 罗马数:

#include 
void Roman(int num, char *Romans);
int main(){
	int i, j;
	char sRom[51];
	
	printf("Roman numerals from 1 to 100:\n");
	for (i=1; i<=100; i++){
		if((i-1)%5 == 0){
			printf("\n ");
		}
		
		Roman(i, sRom);
		for(j=0; sRom[j] != '\0'; j++){
			printf("%c", sRom[j]);
		}
		
		for(;j<11; j++){
			printf(" ");
		}
	}
}

void Roman(int num,char *Romans){
	int i, j, iTh, iHa, iTe, iZe;
	
	iTh = num / 1000;		//千位 
	num = num % 1000;
	
	iHa = num / 100;		//百位 
	num = num % 100;
	
	iTe = num / 10;			//十位 
	iZe = num % 10;
	
	j = 0;
	//千位数 
	for (i = 0; i < iTh; i++){
		Romans[j++] = 'M';
	} 
	//百位  100~900
	switch(iHa){
		case 3: Romans[j++] = 'C';			//若为3,不退出,执行3次C 
		case 2: Romans[j++] = 'C';
		case 1: Romans[j++] = 'C';	break;
		case 4: Romans[j++] = 'C';
				Romans[j++] = 'D';	break;	// 500-100
		case 5: Romans[j++] = 'D';	break;
		case 6: Romans[j++] = 'D';
				Romans[j++] = 'C';	break;	//500+100
		case 7: Romans[j++] = 'D';
				Romans[j++] = 'C';
				Romans[j++] = 'C';	break;
		case 8: Romans[j++] = 'D';
				Romans[j++] = 'C';
				Romans[j++] = 'C';
				Romans[j++] = 'C';	break;
		case 9: Romans[j++] = 'C';
				Romans[j++] = 'M';	break;
		default: break;
	} 
	
	//十位  /10~90
	switch(iTe){
		case 3: Romans[j++] = 'X';
		case 2: Romans[j++] = 'X';
		case 1: Romans[j++] = 'X';	break;
		case 4: Romans[j++] = 'X';
				Romans[j++] = 'L';	break;
		case 5: Romans[j++] = 'L';	break;
		case 6: Romans[j++] = 'L';
				Romans[j++] = 'X';	break;
		case 7: Romans[j++] = 'L';
				Romans[j++] = 'X';
				Romans[j++] = 'X';	break;
		case 8: Romans[j++] = 'L';
				Romans[j++] = 'X';
				Romans[j++] = 'X';
				Romans[j++] = 'X';	break;
		case 9: Romans[j++] = 'X';
				Romans[j++] = 'C';	break;
		default: break; 
	} 
	//个位 1~9 
	switch(iZe){
		case 3: Romans[j++] = 'I';
		case 2: Romans[j++] = 'I';
		case 1: Romans[j++] = 'I';	break;
		case 4: Romans[j++] = 'I';
				Romans[j++] = 'V'; 	break;
		case 5: Romans[j++] = 'V'; 	break;
		case 6: Romans[j++] = 'V';
				Romans[j++] = 'I';	break;
		case 7: Romans[j++] = 'V';
				Romans[j++] = 'I';
				Romans[j++] = 'I';	break;
		case 8: Romans[j++] = 'V';
				Romans[j++] = 'I';
				Romans[j++] = 'I';
				Romans[j++] = 'I';	break;
		case 9: Romans[j++] = 'I';
				Romans[j++] = 'X';	break;
		default: break;
	} 
	Romans[j++] = '\0'; 	
}

运行结果:

罗马数制__十进制数与罗马数的转换__数字分离_第1张图片


三、任意罗马数字 转换为 十进制整数

(待续)

你可能感兴趣的:(C语言实例精粹)