function help

Started by miliham, February 14, 2005, 10:57:08 AM

Previous topic - Next topic
help i need to create a function that will change a roman numeral into a decimal numeral
any help you give will be good thx

February 16, 2005, 03:15:53 PM #1 Last Edit: February 16, 2005, 03:16:44 PM by Metgod
Hey,

I don't actually know roman numerals except for the first 10 or so, but I can perhaps suggest (one) way to do this...

Note that this way is extremely simplistic, and I would guess there are other ways (including possibly better ways). Basically it makes a struct with two members (the string for the roman digits, and the numbers for the decimal equivalents). Then, it scans through the list (after it's created) and when it finds a match it breaks out of a loop. If the loop finishes without a match, it reports it and exits. Otherwise, it simply will print the result.

Also, you'll have to do more complex calculations.. i.e., when you combine things (because it'd be rather innefficient or if nothing else, very troublesome to have to repeatedly change the program). So if you use something like this, you'll want to come up with an algorithm to do more than what I'm showing (translating certain characters to decimal).


#define MAX_CHARS 2
/* define the MAX_CHARS to how many elements are in the array + 1 (+1 for the terminating entry!) */

struct roman_numbers
{
  int decimal;
  char roman;
};

/* Setup an array for the conversion routine .... */
const struct roman_numbers roman[MAX_CHARS+1] =
 {
  { 1, "I" },
  { 2, "II" },
  { -1, "\n" } /* terminating entry -- must be last for code below! */
 };

int roman_conv(char *the_roman)
{
 int i;
 for (i = 0; roman.decimal != -1 ; i++)
       if (!strcmp(roman.roman, the_roman))
               break;

 if (roman.decimal == -1)
       {
       printf("Couldn't match that string.\n");
       return 0;
       }
 printf("%s is Roman Numberal for %d.\n", roman.roman, roman.decimal);
 return 1;
}
int main()
{
roman_conv("II");
return 0;
}

Naturally, you can change the main routine to allow for run time specifying of the characters to convert.

Hope that it helps. I would sugget doing some more research even if only for future reference on how to come up with things.

Cheers,
Met
"My Terminal is my Soul"

just off the top of my head you could probably do it using a switch statement and then dropping the results into custom strings (maybe not though, I haven't written anything out). If I get a chance I'll take a closer look, but I think Metty's solution would work fine too. Cheers
Godaigo
All's fair in Love and Brewing.

SMF spam blocked by CleanTalk