Code Snippets

  

C Source Code


Welcome to Dream.In.Code
Become an Expert!

Join 149,630 Programmers for FREE! Get instant access to thousands of experts, tutorials, code snippets, and more! There are 2,056 people online right now. Registration is fast and FREE... Join Now!





A roman numbers conversion (tested and working)

function to convert unsigned ints into roman numbers, extensible (i just dunno about letter to use when number is 5000 or something, so i stuck with 1000 (roman M)). Syntax of roman numbers are described here: http://www.python.org/dev/peps/pep-0313/

Submitted By: temporary
Actions:
Rating:
Views: 2,125

Language: C

Last Modified: April 25, 2007
Instructions: see main() function about how to use. also, you can extend arrays to get greater roman literals support.

Snippet


  1. /*
  2. Idea to write and post this code born after http://www.dreamincode.net/code/snippet832.htm wrong code review
  3. */
  4. #include <stdio.h>
  5.  
  6. unsigned int  roman_ranges[] = { 1000900500400100905040109,   5,   4,   10 };
  7. unsigned int  roman_addsin[] = {-1000, +100, -500, +100, -100, +10, -50, +10, -10, +1,  -5,  +1,  -10 };
  8. char         roman_letters[] = { 'M',   'C''D''C''C', 'X', 'L', 'X', 'X', 'I', 'V', 'I', 'I', 0 };
  9.  
  10. size_t find_index(unsigned int li) {
  11.     unsigned int *roman_ranges_ptr = roman_ranges;
  12.     while (*roman_ranges_ptr && li < *roman_ranges_ptr) {
  13.         ++roman_ranges_ptr;
  14.     }
  15.     return roman_ranges_ptr - roman_ranges;
  16. }
  17.  
  18. char* uint2roman(unsigned int li, char* buf, size_t bufsize) {
  19.     size_t index;
  20.     if (bufsize < 1) {
  21.         return NULL; // buffer size is not enough for convertion
  22.     }
  23.     if ( (*buf = roman_letters[ (index = find_index(li)) ]) ) {
  24.         return uint2roman(li + roman_addsin[index], buf+1, bufsize-1);
  25.     }
  26.     return buf;
  27. }
  28.  
  29. #define ROMAN_NUMBER_BUF_SIZE 64
  30. int main() {
  31.     unsigned int nr;
  32.     char roman_str[ROMAN_NUMBER_BUF_SIZE];
  33.  
  34.     printf("%s", "Enter an integer: ");
  35.     scanf("%lu", &nr);
  36.     if (uint2roman(nr, roman_str, ROMAN_NUMBER_BUF_SIZE)) {
  37.         printf("Your roman number is %s\n", roman_str);
  38.     } else {
  39.         printf("%s", "Bad roman number or buffer size too small\n");
  40.     }
  41. }
  42.  

Copy & Paste


Comments


There are currently no comments for this snippet. Be the first to comment!

Add comment


You must be registered and logged on to </dream.in.code> to leave comments.




Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter

Live Help!

Tutorials

Programming

Web Development

Reference Sheets

Code Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month