我正在尝试从输入中收集操作数(+、-、*、/)。当我尝试这样做时,* 和/输入被接受,并且代码可以工作。当我输入 + 或 - 时,会抛出默认异常。
这是怎么回事?! getchar 中的 + 或 - 符号是否存在某种问题?我可以尝试根据 ascii 值引用它吗?
我把它当作一个 float ,然后我得到char。这可能是问题所在吗?
float result = 0.0;
float userEntry = 0.0;
char getOperand;
void main(){
printf("Calculator is on\n");
printf("Initial value is 0.0, please issue an operation in the following format: ex. +5 -5 *5 or /5. Do not add more than one number to the total.\n");
scanf("%3f", &userEntry);
getOperand = getchar();
printf("%f", userEntry);
putchar(getOperand);
switch(getOperand){
case '+':
printf("addition\n");
break;
case '-':
printf("subtraction\n");
break;
case '/':
printf("division\n");
break;
case '*':
printf("multiplication\n");
break;
default:
printf("UnknownOperatorException is thrown.\n");
break;
}
}
最佳答案
问题是 +5 和 -5 被 scanf
函数读取为 5 和 -5,而 getchar
函数没有读取任何内容。/和 * 无法被给定格式的 scanf
识别,一旦达到这些,读取就会停止,将它们留给 getchar
。
相反,您可以尝试在调用 scanf
之前调用 getchar
。
下面是它的工作示例,只需将调用切换到 scanf
和 getchar
即可:
输入:
+5
输出:
Calculator is on
Initial value is 0.0, please issue an operation in the following format: ex. +5 -5 *5 or /5. Do not add more than one number to the total.
5.000000+addition
关于C 编程 : getchar() won't accept '+' or '-' for input, 但会接受 '*' 和 '/' 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37633921/