问题
I need help with a coding assignment.
Write an even better calculator program calc3.cpp(Using iostream only) that can understand squared numbers. We are going to use a simplified notation X^ to mean X^2. For example, 10^ + 7 - 51^ should mean 10^2 + 7 − 51^2. Example: When reading input file formulas.txt
5^;
1000 + 6^ - 5^ + 1;
15^+15^;
the program should report:
$ ./calc3 < formulas.txt
25
1012
50625
A hint: To take into account ^, don’t add or subtract new numbers right away after reading them. Instead, remember the number, read the next operator and if it is a ^, square the remembered number, then add or subtract it.
What I have so far:
#include <iostream>
using namespace std;
int main()
{
int numbers,firstnum;
char operators ; // for storing -+;^ from the txt file
int sum = 0;
cin >> firstnum; // stores the 1st integer of the expression found in the txt file.
while(cin >> operators >> numbers)
{ // while loop for storing characters and int
if(numbers>=0 and operators =='+')//adding
{
firstnum+=numbers;
}
else if (numbers>=0 and operators == '-')//subtracting
{
firstnum-=numbers;
}
if (operators==';') // semicolon:ends the loop for each expression
{
cout<<firstnum<<'\n';
firstnum=0+numbers;
}
}
sum=firstnum; // for the last expression not picked up by the while-loop
cout<<sum;
}
I need help constructing a while loop so the '^' doesn't break the loop.
回答1:
In the terminology of parsing, ^
has higher precedence than +
and -
. That is, ^
must be applied first before additions and subtractions are evaluated. You shouldn't add/subtract a number before knowing whether the next token after the number is a ^
; because if it is, then you need to perform the squaring operation first.
Consider, for example, the following input file:
1 + 3^;
Right now, your program will read 1
and store this in firstnum
. Then your program reads +
(storing this in operators
) and 3
(storing this in numbers
). Then your program reaches the numbers>=0 and operators =='+'
case, so firstnum+=numbers;
is evaluated and firstnum
becomes 4. But, this is a mistake, because the next token is a ^
, so the 3 should have been squared first.
Consider this other example:
4^ + 1;
Your program currently reads 4
into firstnum
, ^
into operators
, and then tries to parse +
as an integer. This fails, causing the fail bit to be set on cin
and cin >> operators >> numbers
evaluates to false
.
One special case that you might want to handle is when an expression begins with a -
:
-9^; -10^ + 11^;
Also, you might want to ask for clarification as to how the following should be handled:
1^ + -2^; 1^ - -2^; 2^^^;
来源:https://stackoverflow.com/questions/49101581/task-d-calc3squares-how-to-construct-a-proper-loop-for-my-assignment-c