基本上,我正在编写一个实现累加器的简单命令行计算器。我觉得这段代码在逻辑上是正确的,我不明白为什么它在进入无限循环的打印语句之前冻结大约3秒。任何帮助都是非常感谢的。
void mycalc() {
printf("Begin Calculations\n\n");
printf("Initialize your Accumulator with data of the form \"number\" \"S\" which\
sets the Accumulator to the value of your number\n");
/* Initialize Variables */
float accumulator, num;
char op;
/* Ask for input */
scanf("%f %c\n", &num, &op);
while (op != 'E') {
if(op == 'S' || op == 's'){
accumulator = num;
printf("Value in the Accumulator = %f\n", accumulator);
} else if(op == '+'){
accumulator = accumulator + num;
printf("Value in the Accumulator = %f\n", accumulator);
} else if(op == '*'){
accumulator = accumulator * num;
printf("Value in the Accumulator = %f\n", accumulator);
} else if(op == '/'){
if (num == 0) {
printf("Can not divide by 0.\n");
} else {
accumulator = accumulator / num;
printf("Value in the Accumulator = %f\n", accumulator);
}
} else if(op == '-'){
accumulator = accumulator - num;
printf("Value in the Accumulator = %f\n", accumulator);
} else if(op == 'E' || op == 'e'){
printf("Value in the Accumulator = %f\n", accumulator);
break;
} else {
printf("Unknown operator. \n");
}
scanf("%f %c\n", &num, &op);
}
}用时间(1)技术代替更好吗?任何和所有的帮助都是感激的!谢谢!
发布于 2013-09-24 01:43:30
代码不能很好地处理错误的输入。
在两个地方,如果输入非数字输入,scanf("%f %c\n", &num, &op)会遇到麻烦。scanf()失败,因此num和op保留它们的旧值。基于op的操作再次发生,下一个scanf()使用相同的数据再次尝试。
两个地方的"%f %c\n"具有误导性,因为\n的执行方式与OP预期不同。变到
scanf("%f %c", &num, &op);与其使用scanf(),不如使用
char buf[100];
if (fgets(buf, sizeof(buf), stdin) == NULL) {
exit(-1); // handle EOF or error
}
if (sscanf(buf, "%f %c", &num, &op) != 2) {
exit(-1); // syntax error.
}另一种选择是可以使用以下方法。糟糕的输入最终会被消耗掉,但不那么容易。
if (2 != scanf(" %c %f", &op, &num)) {
; // syntax error.
}其他问题:未初始化累加器
float accumulator = 0.0;https://stackoverflow.com/questions/18971443
复制相似问题