C/C++ Programming Learning-Week 6⑧ Simple Calculator

Topic link

Title description

The garlic master has one of the simplest calculators, which supports four operations:'+','-','*', and'/'.

It is only necessary to consider the case where the input and output are integers, and the data and operation results will not exceed the range represented by int.

Input format The
input is only one line, and there are three parameters in total. The first and second parameters are integers, and the third parameter is operators ('+','-','*','/' or other symbols).

Output format The
output is only one line, an integer, which is the result of the operation. however:

If the divisor is 0, the output is: "Divided by zero!";
if there is an invalid operator (that is, it is not one of'+','-','*','/'), the output is: "Invalid operator!".

Sample Input

1 2 +

Sample Output

3

Ideas

It is equivalent to the calculation of the postfix expression, but only addition, subtraction, multiplication and division.

C++ code:

#include<bits/stdc++.h>
using namespace std;
int main()
{
    
    
	int a, b;
	char c;
	while(cin >> a >> b >> c)
	{
    
    
		if(c == '+') cout << a + b << endl;
		else if(c == '-') cout << a - b << endl;
		else if(c == '*') cout << a * b << endl;
		else if(c == '/')
		{
    
    
			if(b == 0) cout << "Divided by zero!" << endl;
			else cout << a / b << endl;
		}
		else cout << "Invalid operator!" << endl;
	}
	return 0;
}

For students who don’t have C language foundation, you can learn the C language grammar first. I will sort it out and send it out later.
I have already written it. You can go to the C language programming column to see the content of the first week .

Other exercises this week:

C language programming column

C/C++ Programming Learning-Week 6① Calculate A+B (Novice Course)

C/C++ programming learning-week 6② A*B problem

C/C++ Programming Learning-Week 6 ③ Class size

C/C++ Programming Learning-Week 6 ④ Sum of odd numbers

C/C++ Programming Learning-Week 6 ⑤ Calculation of the bounce height of the ball

C/C++ Programming Learning-Week 6 ⑥ Image similarity

C/C++ Programming Learning-Week 6 ⑦ Separate each digit of an integer

C/C++ Programming Learning-Week 6⑧ Simple Calculator

Guess you like

Origin blog.csdn.net/qq_44826711/article/details/112911972