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