Use C++ to complete a calculator (overall structure + source code)

This article will introduce how to write a simple calculator using C++. We'll cover basic operations, input and output, error handling, and some interesting features. We will comprehensively introduce the development process of the calculator from the aspects of design ideas, code implementation, testing and debugging.

1. Design ideas

Before we start writing code, we need to think about how the calculator is designed. We need to consider the following aspects:

1. Basic operations: addition, subtraction, multiplication, division, remainder, etc.

2. Input and output: how to obtain user input and output operation results.

3. Error handling: How to deal with illegal characters and exceptions entered by users.

4. Advanced functions: How to implement advanced functions such as brackets, scientific notation, square root, and factorial.

We need to design the overall framework and functional modules of the calculator based on the above aspects. We can use an object-oriented approach to encapsulate each functional module into a class. When implementing the code, we can implement the basic operation functions first, then gradually add advanced functions, and finally test and debug.

2. Code implementation

1. Basic operation

We need to define a Calculator class, which includes basic operations such as addition, subtraction, multiplication, division, and remainder. We can use the switch statement to implement the selection of basic operations, and use cin and cout for input and output. code show as below:

```c++
class Calculator {
public:
    void add(double a, double b) {
        cout << a + b << endl;
    }
    void sub(double a, double b) {
        cout << a - b << endl;
    }
    void mul(double a, double b) {
        cout << a * b << endl;
    }
    void div(double a, double b) {
        if (b == 0) {
            cout << "Error: Divisor cannot be zero!" << endl;
            return;
        }
        cout << a / b << endl;
    }
    void mod(double a, double b) {
        if (b == 0) {
            cout << "Error: Divisor cannot be zero!" << endl;
            return;
        }
        cout << fmod(a, b) << endl;
    }
};
```

2. Input and output

We need to define an Input class and an Output class, which are used to obtain user input and output operation results respectively. We can use cin and cout to implement input and output functions. code show as below:

```c++
class Input {
public:
    double getNumber() {
        double number;
        cin >> number;
        return number;
    }
};
class Output {
public:
    void printResult(double result) {
        cout << "Result: " << result << endl;
    }
};
```

3. Error handling

We need to add an error handling function to the Calculator class to handle illegal characters and exceptions entered by the user. For example, when the divisor entered by the user is 0, we need to output an error message and return. code show as below:

```c++
void div(double a, double b) {
    if (b == 0) {
        cout << "Error: Divisor cannot be zero!" << endl;
        return;
    }
    cout << a / b << endl;
}
```

4. Advanced Features

We can use data structures such as recursion and stacks to implement advanced functions such as parentheses, scientific notation, square roots, factorials, etc. For example, when the user enters an expression, we can use the stack to process the parentheses and use recursion to process the expression inside the parentheses. code show as below:

```c++
void calculate(string str) {
    stack<char> s;
    int len = str.size();
    for (int i = 0; i < len; i++) {
        if (str[i] == '(') {
            s.push(str[i]);
        }
        else if (str[i] == ')') {
            if (s.empty()) {
                cout << "Error: Invalid input!" << endl;
                return;
            }
            s.pop();
        }
    }
    if (!s.empty()) {
        cout << "Error: Invalid input!" << endl;
        return;
    }
    double result = calculate_helper(str, 0, len - 1);
    cout << "Result: " << result << endl;
}
double calculate_helper(string str, int start, int end) {
    int flag = 0;
    for (int i = end; i >= start; i--) {
        if (str[i] == ')') {
            flag++;
        }
        else if (str[i] == '(') {
            flag--;
        }
        if (flag == 0 && (str[i] == '+' || str[i] == '-')) {
            double left = calculate_helper(str, start, i - 1);
            double right = calculate_helper(str, i + 1, end);
            if (str[i] == '+') {
                return left + right;
            }
            else {
                return left - right;
            }
        }
    }
    flag = 0;
    for (int i = end; i >= start; i--) {
        if (str[i] == ')') {
            flag++;
        }
        else if (str[i] == '(') {
            flag--;
        }
        if (flag == 0 && (str[i] == '*' || str[i] == '/')) {
            double left = calculate_helper(str, start, i - 1);
            double right = calculate_helper(str, i + 1, end);
            if (str[i] == '*') {
                return left * right;
            }
            else {
                if (right == 0) {
                    cout << "Error: Divisor cannot be zero!" << endl;
                    exit(0);
                }
                return left / right;
            }
        }
    }
    flag = 0;
    for (int i = end; i >= start; i--) {
        if (str[i] == ')') {
            flag++;
        }
        else if (str[i] == '(') {
            flag--;
        }
        if (flag == 0 && str[i] == '%') {
            double left = calculate_helper(str, start, i - 1);
            double right = calculate_helper(str, i + 1, end);
            if (right == 0) {
                cout << "Error: Divisor cannot be zero!" << endl;
                exit(0);
            }
            return fmod(left, right);
        }
    }
    if (str[start] == '(' && str[end] == ')') {
        return calculate_helper(str, start + 1, end - 1);
    }
    if (str[start] == '-') {
        return -calculate_helper(str, start + 1, end);
    }
    double result = 0;
    double base = 10;
    int index = 0;
    for (int i = start; i <= end; i++) {
        if (str[i] == '.') {
            index = i + 1;
            break;
        }
        else if (isdigit(str[i])) {
            result = result * base + (str[i] - '0');
        }
    }
    double factor = 0.1;
    for (int i = index; i <= end; i++) {
        if (isdigit(str[i])) {
            result = result + (str[i] - '0') * factor;
            factor = factor * 0.1;
        }
    }
    return result;
}
```

3. Testing and Debugging

After completing the code implementation, we need to test and debug. We can write some test cases to test various functions of the calculator. For example, we can test basic operations such as addition, subtraction, multiplication, division, and remainder, as well as advanced functions such as parentheses, scientific notation, square root, and factorial. If testing finds a problem, we need to debug to find out what went wrong and fix it.

Four. Summary

Through the introduction of this article, we can understand how to use C++ to write a simple calculator. We need to consider the design ideas of the calculator and implement modules such as basic operations, input and output, error handling, and advanced functions. When implementing code, we can use object-oriented methods to encapsulate each module into a class, and use data structures such as recursion and stacks to achieve advanced functions. When testing and debugging, we need to write some test cases, test various functions of the calculator, and debug and fix problems.

Guess you like

Origin blog.csdn.net/q6115759/article/details/130015054#comments_25928100