# Exercise 6-7 simple calculator (super detailed! Structured programming step analysis) (20 points)

Posted by MikeSpider on Fri, 04 Mar 2022 23:49:14 +0100

### Exercise 6-7 simple calculator (20 points)

Simulate the operation of a simple arithmetic unit. Assuming that the calculator can only perform addition, subtraction, multiplication and division, and the operands and results are integers, the four operators have the same priority and are calculated from left to right.

### Input format:

Input gives a four arithmetic expression in one line, with no spaces and at least one operand. When an equal sign "=" indicates the end of input.

### Output format:

Output the operation result of the formula in one line, or if the division denominator is 0 or there is an illegal operator, output the ERROR message "ERROR".

### Input sample:

`1+2*10-10/2=`

`10`

## [Topic meaning understanding and segmentation task]

Step 1: calculation process analysis of output data: 1 + 2 * 10-10 / 2 = 10

① First calculate 1 + 2 = 3 ② calculate 3 * 10 = 30 ③ calculate 30-10 = 20 ④ calculate 20 / 10 = 2 ⑤ encounter the equal sign output result

Step 2: clarify the logic and edit the algorithm

Several problems that may be encountered in the algorithm transformation process of problem solving:

Question ① how to deal with the input data with both numbers and operators?

Question ② how to realize the sequential calculation from left to right

### analysis:

For problem ①: obviously, the knowledge we have learned is not enough to support us to input the whole formula at one time, so we should process the input data in batches.

This leads to new problems: problem ③ how to cycle the input data in batches, what are the conditions of the cycle, problem ④ how to batch and according to what to segment the data.

To solve the problem ③: because the number of cycle control is uncertain, but we know that the cycle can be ended when the input character data is' = ', so the while cycle is preferred to realize this problem. While (character variable! = '=') {   }

For problem ④: Based on known conditions,

"Input gives a four arithmetic expression in one line, with no spaces and at least one operand.",

It can be determined that the initial input format is scanf ("% d% C", & first integer variable, & character variable); The input condition of the character is obtained by the judgment of the cyclic variable.

After entering the cycle, the next problem to be solved is problem ② how to realize the sequential calculation from left to right

In the initial input process, we have entered a number and an operator. After entering the loop, we need to call scanf ("% d", & the second integer variable) to obtain the second operand, and then continue the calculation. The next step is to determine the calculation method according to the previously entered operator.

For this kind of selective branch statement with a few fixed judgment conditions, it is best to use the switch () statement: because it is used less, it is supplemented as follows

See the textbook: p57-p60 for details

### Switch() statement details To solve problem ②, we can use the calculation principle of sum = sum+ i to save the calculation result in the first integer variable. The first integer = the second integer variable;

The basic logic is clear, and the large framework is basically completed, followed by special condition processing and boundary control.

Output the operation result of the formula in one line, or if the division denominator is 0 or there is an illegal operator, output the ERROR message "ERROR".

This condition is relatively simple. Let's try to write code directly.

### Write preliminary code synthesis:

```#include <stdio.h>

int main()
{
int x;  //The data before the operator is stored in the variable x
int y;  //Operator exists in y
char ch;

scanf("%d%c", &x, &ch);
while(ch!='='){       //Operator is legal. Continue to enter data

scanf("%d",&y);   //Start entering the second data

switch(ch){
case '+': x += y; continue;
//After executing this statement, I wanted to skip the following statements directly and continue to restart the next cycle
case '-': x -= y; continue;
case '*': x *= y; continue;
case '/':
if(y!=0) {
x /= y;
continue;
}
else  if(y == 0)
printf("ERROR");break;

default :printf("ERROR");break;

}
scanf("%c",&ch);  //Change of cycle conditions
}//while
printf("%d", x);

return 0;
}
``` oh dear! The compiler reported an error.

: because the switch statement is a selection statement, it can only be used with break +, and continue can only be used in the loop statement. Although it is nested in the loop statement, an error occurred due to the scope

main.c:14:35: Error: 'continue' is only allowed inside loop statements.
case '+': x += y; continue;

### Error analysis and debugging

Our basic logic is to jump out of switch () and execute the following statement to carry out the next cycle.

After the initial compilation, I found a major grammatical detail.

Because the switch statement is a selection statement, you can only use break, and continue can only be used in circular statements (long memory!)

Replace all continue statements in the above code with break statements and continue debugging and verification:

\$ ./main
1 + 2 * 10-10 / 2 = / / input the sample and output it successfully
10     Program exited with status 0

Try dividing by 0

\$ ./main
125/0=
ERROR125    Program exited with status 0

\$ ./main
125&5=
ERROR125   Program exited with status 0

//It is found that there is a small problem in the logic of the input sample. After an error occurs, all subsequent information cannot be interrupted The solution is to set an error flag variable flag = 0 and set the initial value. After the error, the flag bit is modified, such as flag = 1;

Then set the mark check after the switch () statement. If the mark is modified, it will jump out of the loop. At the last output, it is necessary to judge the information of the mark bit and print it by classification to realize the final classified output.

### The complete and detailed code is as follows:

```#include <stdio.h>

int main()
{
int x;  //The data before the operator is stored in the variable x
int y;  //Operator exists in y
int flag = 0; //Error flag bit, error will modify the value of the flag variable
char ch;//A variable that stores input characters

scanf("%d%c", &x, &ch);
while(ch!='='){       //Operator is legal. Continue to enter data

scanf("%d",&y);   //Start entering the second data

switch(ch){     //switch statement realizes the classification operation of addition, subtraction, multiplication and division
case '+': x += y; break;  //The break implementation jumps out of the switch statement
case '-': x -= y; break;
case '*': x *= y; break;
case '/':
if(y!=0) {   //The conditional judgment statement realizes the judgment of denominator error
x /= y;
break ;
}
else{
flag = 1 ;  //Error modifying the value of flag bit
break ;
}
default :flag = 1 ; break;  //Illegal character judgment
}
if(flag==1) break;  //If the error judgment flag bit is modified, the break will jump out of the while loop

scanf("%c",&ch);  //****Note: change the while loop condition, otherwise the loop will die*******
}//while

if(flag==1)   //Realize classified output
printf("ERROR");
else
printf("%d", x); //Correct output
return 0;
}
```

Finally, do simple optimization and delete simple notes: get

# Code of pure version:

```#include <stdio.h>

int main()
{
int x,y,flag=0;
char ch;

scanf("%d%c", &x, &ch);
while(ch!='='){       //Operator is legal. Continue to enter data

scanf("%d",&y);

switch(ch){     //switch statement realizes the classification operation of addition, subtraction, multiplication and division
case '+': x += y; break;
case '-': x -= y; break;
case '*': x *= y; break;
case '/':
if(y!=0) {
x /= y;
break ;
}
else{
flag = 1 ;
break ;
}
default :flag = 1 ; break;
}
if(flag==1) break;  //Wrong judgment

scanf("%c",&ch);  //: change of while loop condition
}

if(flag==1)
printf("ERROR");
else
printf("%d", x);
return 0;
}

Develop good code writing practices from the beginning:
Write only one sentence in one line, and divide the task module into blocks in an empty line, and adjust the indentation
Make your code more intuitive, easy to understand, easy to debug and more beautiful!
``` ## ***

■ use scenarios and limiting conditions of break, and continue.

■ the algorithmic thinking and implementation process of disassembling and classifying a whole block of input conditions.

■ format of switch () statement.

■ if there is an error in the loop, how to jump out of the loop and do not conflict with the final output  Topics: C Algorithm