簡體   English   中英

簡單的C代碼進入無限循環。 為什么?

[英]Simple C Code going into Infinite Loop. Why?

基本上,我正在編寫一個實現累加器的簡單命令行計算器。 我覺得這段代碼在邏輯上是正確的,而且我不明白為什么它進入打印語句的無限循環之前會凍結約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()再次嘗試使用相同的數據。

"%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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM