【问题标题】:Writing a C++ calculator program that runs one more instance than needed编写一个 C++ 计算器程序,它运行的实例比需要的多一个
【发布时间】:2018-09-17 12:59:06
【问题描述】:

因此,对于课堂项目,我需要创建一个计算器程序,该程序从包含以下公式的文本文件 formula.txt 中获取输入:

'15 ;
10 + 3 + 0 + 25 ;'

当程序运行时,它应该计算并打印公式的结果,换行符如下:

15 38

但是,每次我运行程序时,它都会给我以下结果:
15 38 25

我已经检查了我的代码,但没有发现问题。任何帮助,将不胜感激。通过代码在下面找到。

#include <iostream>
using namespace std;

int main ()
{
  double input; //initialize input variable
  char sign; //intialize sign character
  double calc = 0; //initial calculation value set to 0
  bool add= true; // add to use whether to add or not
  bool cont = true; // boolean for continuing loop

  while (cont) //loop only continues while cont is true
  {

    cin >> input; //take in input

    if (add)  //if add is true
    {
      calc = calc + input; // adds the input to calc
    }

    else //if add is false
    {
      calc = calc - input; //subtracts input from calc
    }

    cin >> sign; //take in sign

    if (sign == '+') //if sign is '+'
    {
      add = true; //add is true
    }

    else if (sign == '-') //if sign is '-'
    {
      add = false; //add is false
    }

    else if (sign == ';') //if sign is ';'
    {
      cout << calc << endl; //outputs calc to console
      calc = 0;
    }

    if (cin.fail()) // if cin fails
    {
      cont = false; //continue is set to false
    }

  }
  return 0;
}

【问题讨论】:

  • 提示:什么时候检查cin &gt;&gt; input;是否成功?
  • 底部带有'if (cin.fail())'
  • 不是当前的问题,但它会是你遇到的下一个问题:如果一个表达式的最后一个操作是-,则下一个表达式的第一个值将不会添加到@ 987654328@
  • 基本上是this的骗子。 TL;DR:始终使用读取操作作为循环的条件。
  • 剧透 molbdnilos 评论:你先获取输入,然后使用值,然后检查输入是否成功。现在试着找出这个订单有什么问题;)

标签: c++ calculator


【解决方案1】:

问题来自您的循环。 你打印 38. if(cin.fail()) 是假的,你之前的 cin 插入 ';'签到就好了。

所以再转一圈。 add 是真的,所以 calc 是 calc + 输入。你的最后一个输入是 25,所以 calc = 25。

cin >> 符号失败。你的最后一个标志是';'所以你在 cout -> 25 中打印 calc。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-23
    • 2016-10-30
    • 1970-01-01
    • 1970-01-01
    • 2015-07-28
    • 1970-01-01
    • 2020-04-04
    相关资源
    最近更新 更多