开发者社区> 问答> 正文

用 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 - 并回车,都会反应如下:程序就会仍然等待输入,而不是直接返回计算结果;若在-后多输入一个空格再回车,倒能返回正确计算结果。

展开
收起
a123456678 2016-06-06 11:45:39 2079 0
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 时可能会出问题。

    2019-07-17 19:28:06
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载