用 C 写简易计算器,需要能处理负数

Updated: 在下搞错本人在 GitHub 上的 solution 提交历史了,现重新提交并更新本问题。


题目出自 K&R 中的 Exercise 4-3:

Given the basic framework, it's straightforward to extend the calculator. Add the modulus ( % ) operator and provisions for negative numbers.

但是,在本人自认为理论上应该正确的 solution, 还是 Bob Wightman 的 solution 中,只要在程序输入 12 34 - 并回车,都会反应如下:程序就会仍然等待输入,而不是直接返回计算结果;若在-后多输入一个空格再回车,倒能返回正确计算结果。

到底该如何 Fix 呢?谢谢!

阅读 4.1k
1 个回答
diff --git a/Chapter 4/4-3/getch.c b/Chapter 4/4-3/getch.c
index 316520b..4525655 100644
--- a/Chapter 4/4-3/getch.c     
+++ b/Chapter 4/4-3/getch.c     
@@ -37,5 +37,5 @@ extern void ungetch(const char c) {
   if (buf_free_position > BUFFERSIZE)
     printf("Error: buffer full, can not push %c\n", c);
   else
-    buf[buf_free_position] = c;
+    buf[buf_free_position++] = c;
 }

另外注意 getchar 的原型是 int getchar(void);,你用 char 来存的话在判断 EOF 时可能会出问题。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进