1

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

4

1 回答 1

1

代码不能很好地处理错误的输入。

scanf("%f %c\n", &num, &op)如果输入非数字输入,则在两个地方有问题。scanf()失败了,所以numop保留了他们的旧价值观。基于的操作op再次发生,下一次使用相同的数据scanf()再次尝试。

"%f %c\n"2 个地方具有误导性,因为其\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;
于 2013-09-24T01:43:30.427 回答