Home  >  Article  >  Backend Development  >  Powerful functions: Use Go language to implement four arithmetic operations to easily cope with complex operation requirements

Powerful functions: Use Go language to implement four arithmetic operations to easily cope with complex operation requirements

PHPz
PHPzOriginal
2024-02-26 14:36:121095browse

Powerful functions: Use Go language to implement four arithmetic operations to easily cope with complex operation requirements

Title: Powerful: Use Go language to implement four arithmetic operations, easily coping with complex operation requirements

With the development of the computer field, the four arithmetic operations are the most basic mathematical operations One, often widely used in various types of software development. In order to better meet complex computing needs, many developers use efficient programming languages ​​​​such as the Go language to implement related functions. This article will introduce how to use Go language to implement four arithmetic operations, from simple addition, subtraction, multiplication and division to complex operations that support parentheses and precedence, helping readers easily solve calculation problems.

First of all, we need to clarify the basic principles of the four arithmetic operations. The four arithmetic operations include addition, subtraction, multiplication and division. The calculation order can be determined by sequential calculation or based on parentheses and priority. In Go language, we can implement these functions by defining structures and methods. The following is a simple Go language program that implements the basic four arithmetic functions:

package main

import (
    "fmt"
)

type Operation struct {
    operand1 float64
    operand2 float64
}

func (op Operation) Add() float64 {
    return op.operand1 + op.operand2
}

func (op Operation) Subtract() float64 {
    return op.operand1 - op.operand2
}

func (op Operation) Multiply() float64 {
    return op.operand1 * op.operand2
}

func (op Operation) Divide() float64 {
    if op.operand2 != 0 {
        return op.operand1 / op.operand2
    } else {
        return 0
    }
}

func main() {
    op := Operation{operand1: 10, operand2: 5}
    
    fmt.Println("加法结果:", op.Add())
    fmt.Println("减法结果:", op.Subtract())
    fmt.Println("乘法结果:", op.Multiply())
    fmt.Println("除法结果:", op.Divide())
}

In the above example, a Operation structure is defined, containing two operandsoperand1 and operand2, and implement four operations methods of addition, subtraction, multiplication and division respectively. In the main function, an Operation object is created, these methods are called respectively and the results are printed.

In addition to the basic four arithmetic operations, sometimes we also need to process complex operation expressions containing parentheses and precedence. This can be achieved with the help of the stack data structure. The following is an example of a Go language program that implements four arithmetic operations with parentheses and precedence:

package main

import (
    "fmt"
    "strconv"
    "strings"
)

func calculate(expression string) float64 {
    expression = strings.ReplaceAll(expression, " ", "") // 去除空格
    stack := []string{}
    tokens := strings.Split(expression, "")

    for _, token := range tokens {
        if token == "(" {
            stack = append(stack, token)
        } else if token == ")" {
            var current string
            for {
                current, stack = stack[len(stack)-1], stack[:len(stack)-1]
                if current == "(" {
                    break
                }
                result, _ := strconv.ParseFloat(current, 64)
                stack = append(stack, strconv.FormatFloat(result, 'f', -1, 64))
            }
        } else {
            stack = append(stack, token)
        }
    }

    for len(stack) > 1 {
        op2, _ := strconv.ParseFloat(stack[len(stack)-1], 64)
        op1, _ := strconv.ParseFloat(stack[len(stack)-3], 64)
        operator := stack[len(stack)-2]
        var result float64

        switch operator {
        case "+":
            result = op1 + op2
        case "-":
            result = op1 - op2
        case "*":
            result = op1 * op2
        case "/":
            result = op1 / op2
        }

        stack = stack[:len(stack)-3]
        stack = append(stack, strconv.FormatFloat(result, 'f', -1, 64))
    }

    result, _ := strconv.ParseFloat(stack[0], 64)
    return result
}

func main() {
    expression := "(10 + 5) * 2"
    result := calculate(expression)
    fmt.Println("复杂运算结果:", result)
}

In the above example, the calculate function can express complex operations involving parentheses and precedence. Calculate the formula. The bracket structure of the expression is processed through the stack, and the final result is calculated sequentially according to the priority of the four arithmetic operations. In the main function, we define an expression containing parentheses (10 5) * 2, and the result is calculated and printed through the calculate function.

In summary, implementing the four arithmetic operations through Go language can not only solve basic operation needs, but also easily handle complex operation expressions containing parentheses and precedence. Developers can optimize the code according to actual needs and achieve more feature-rich computing functions. I hope this article can help readers better understand how to use Go language to implement four arithmetic operations and cope with complex computing requirements.

The above is the detailed content of Powerful functions: Use Go language to implement four arithmetic operations to easily cope with complex operation requirements. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn