Im very new to C, only been doing it a few days, so no doubt I'm making this more complex than it needs to be, but im trying to write a program which will print the argument (given as an int) in roman numeral form. I thought Id just try and write something, not really knowing how to go about this, and got this:
Which spits out random results not what theyre meant to be. Obviously even if this worked, it still isn't taking into account cases like 900, 90, 9, 400, 4, 40 ect. which all use subtraction in their roman numeral form. Still no idea how to implement that part of it.Code:#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> int checkint(char s[]) //Checks if string is purely numerical { int t = 1; // Set t=1 int length = strlen(s); // Define string length for (int i = 0; i < length; i++) // For each character { if (s[i] >= '0' && s[i] <= '9'); // If numerical, then do nothing else t = 0; //If not, then set t=0 } return t; } static void roman(int n) { char r[6]; r[0] = 'M'; r[1] = 'D'; r[2] = 'C'; r[3] = 'L'; r[4] = 'X'; r[5] = 'V'; r[6] = 'I'; int t[6]; t[0] = 1000; t[1] = 500; t[2] = 100; t[3] = 50; t[4] = 10; t[5] = 5; t[6] = 1; int i[6]; for (int a = 0; a < 7; a++) { if (n > t[a]) { i[a] = n / t[a]; n = n - i[a]*t[a]; } else; int b = 0; while (b < i[a]) { printf("%c", r[a]); b++; } } printf("\n"); } int main(int argc, char *argv[]) { if(argc < 2) // Error is number of arguments is less than 2 { fprintf(stderr, "%s: program expected 1 or more arguments, but received %d\n", argv[0], argc-1); exit(EXIT_FAILURE); } else { // Loop for each argument passed to the program for(int i = 1; i < argc; i++) { if (!checkint(argv[i])) // Check arguments provided are numerical { // If not, then exit and give error message fprintf(stderr, "%s: program expected positive numerical arguments\n", argv[0]); exit(EXIT_FAILURE); } else { int n = atoi(argv[i]); // Argument as integer roman(n); // Call roman function /* printf("%d as a Roman Numeral is %s\n", n, s); // Return string */ } } // Exit indicating success exit(EXIT_SUCCESS); } return 0; }
Help would be nice, im totally stuck on this =/



LinkBack URL
About LinkBacks



, well maybe, it might be more complicated I am not 100% of 