基本上我正在编写一个实现累加器的简单命令行计算器。我觉得这段代码的逻辑结构是正确的,我不明白为什么它在进入打印语句的无限循环之前冻结了大约 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) 技术会更好吗?任何和所有的帮助表示赞赏!谢谢!