c - 进入无限循环的简单 C 代码。为什么?

标签 c loops calculator infinite accumulator

基本上,我正在编写一个实现累加器的简单命令行计算器。我觉得这段代码在逻辑结构上是正确的,我不明白为什么它会在进入打印语句的无限循环之前卡住大约 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() 失败,因此 numop 保留其旧值。基于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/

相关文章:

javascript - 计算器清除按钮

c - 为什么指针算术可用于非连续的2d数组?

c - 我在 C 中的字符串 BST 插入后始终为空

c - 设置 Eclipse 使用以下参数调用我的程序 "< fileName.txt"

c++ - 为什么我看不到 "Application Error"对话框?

Python循环等效Excel偏移等效?

java - 使用字符串创建一个长度为 n、高度为 n 的正方形

c++计算器不断循环

c++ - 用 boost spirit 分离 AST 创建和计算

linux - 循环 Linux Shell 的空主体