我有这个程序试图从罗马数字转换为阿拉伯数字并且编译没有问题,但即使我输入一个有效数字,它总是默认显示无效参数。
#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);
}
}
回答1
您没有指定输入,但我认为您使用字符“n”来终止罗马数字。
但是,循环检查:
while ((letraR != 'n') && (cont < 15)) {
和开关盒:
case 'n': break;
永远不会匹配,因为您已经在输入上调用了 toupper()
。
但是,正如其他人在评论中所建议的那样,您可能正在尝试匹配 '\n' 而不是 'n' - 所以您只需要这些条件来检查 '\n'
(换行)而不是 'n'
。