从罗马数字转换为阿拉伯数字的程序总是给出无效参数

Program that converts from roman to arabic numerals always gives Invalid Argument

我有这个程序试图将罗马数字转换为阿拉伯数字并编译 没有问题,但即使我输入了一个有效的数字,它总是默认显示 参数无效。

#include <conio.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

int main () {
   int Rnum = 0;
   int Rdec = 0;
   int cont = 0;
   int cont3R = 0;
   int Rnums[15] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
   char Rletter = ' ';
   char roman[15] = "";
   printf ("Enter a Roman numeral in the range I to MMMCMXCIX:\n");

同时阻止

   while ((Rletter != 'n') && (cont < 15)) {
      Rletter = toupper(getchar());
      switch (Rletter) {
         /* V, L and D can only appear once */
         case 'V': case 'L': case 'D':
            if ((cont > 0) && (roman[cont - 1] == Rletter)) {
                  printf ("\nInvalid argument");
                  sleep(1000);
                  exit(0);
            }

            else { roman[cont++] = Rletter; }
            break;

         case 'I': case 'X': case 'C': case 'M':
            if (cont3R <= 3) {
               roman[cont++] = Rletter;
            }
            cont3R++;
            if ((cont3R > 3) && (roman[cont - 2] == Rletter)) {
               printf ("\nInvalid argument");
               sleep(1000);
               exit(0);
            }
            if ((cont > 1) && ((cont3R > 3) || (roman[cont - 2] != Rletter))) {
               cont3R = 1;
            }
            break;

         case 'n':   break;

         default:    printf("\nInvalid argument"); //<--- It comes out here
                     sleep(1000);
                     exit(0);
     }
   }

您没有指定输入,但我推测您正在使用字符 'n' 来终止罗马数字。

然而,循环检查:

while ((letraR != 'n') && (cont < 15)) {

和开关盒:

case 'n': break;

永远不会匹配,因为您已经在输入中调用了 toupper()

但是,正如其他人在评论中所建议的那样,您可能正在尝试匹配 '\n' 而不是 'n' - 所以您只需要这些条件来检查 '\n' (行return) 而不是 'n'.