我一直在寻找一些关于在目标 c 中从数字转换为罗马数字的示例代码。有人知道我在哪里可以找到一个很好的例子吗?
更新:
没关系,找到了一个 PHP 函数,它可以满足我的需求并移植它。到目前为止似乎工作正常。
-(NSString*)numberToRomanNumerals:(int)num{
if (num < 0 || num > 9999) { return @""; } // out of range
NSArray *r_ones = [[NSArray alloc]initWithObjects:@"I", @"II", @"III", @"IV", @"V", @"VI", @"VII", @"VIII",@"IX",nil];
NSArray *r_tens = [[NSArray alloc]initWithObjects:@"X", @"XX", @"XXX", @"XL", @"L", @"LX", @"LXX",@"LXXX", @"XC",nil];
NSArray *r_hund = [[NSArray alloc]initWithObjects:@"C", @"CC", @"CCC", @"CD", @"D", @"DC", @"DCC",@"DCCC", @"CM",nil];
NSArray *r_thou = [[NSArray alloc]initWithObjects:@"M", @"MM", @"MMM", @"MMMM", @"MMMMM", @"MMMMMM",@"MMMMMMM",
@"MMMMMMMM", @"MMMMMMMMM",nil];
int ones = num % 10;
int tens = (num - ones) % 100;
int hundreds = (num - tens - ones) % 1000;
int thou = (num - hundreds - tens - ones) % 10000;
tens = tens / 10;
hundreds = hundreds / 100;
thou = thou / 1000;
NSString *rnum=@"";
if (thou) { rnum = [rnum stringByAppendingString:[r_thou objectAtIndex:thou-1]]; }
if (hundreds) { rnum = [rnum stringByAppendingString:[r_hund objectAtIndex:hundreds-1]]; }
if (tens) { rnum = [rnum stringByAppendingString:[r_tens objectAtIndex:tens-1]]; }
if (ones) { rnum = [rnum stringByAppendingString:[r_ones objectAtIndex:ones-1]]; }
[r_ones release];
[r_tens release];
[r_hund release];
[r_thou release];
return rnum;
}