基本上,我正在编写一个实现累加器的简单命令行计算器。我觉得这段代码在逻辑结构上是正确的,我不明白为什么它会在进入打印语句的无限循环之前卡住大约 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);
}
}
改用 while(1) 技术会更好吗?任何帮助表示赞赏!谢谢!
最佳答案
代码不能很好地处理错误的输入。
如果输入非数字输入,scanf("%f %c\n", &num, &op)
有两个地方有问题。 scanf()
失败,因此 num
和 op
保留其旧值。基于op
的操作再次发生,下一个scanf()
再次尝试使用相同 数据。
2 个地方的 "%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;
关于c - 进入无限循环的简单 C 代码。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18971443/