Use Golang to implement calculator
With the advancement of science and technology, computers have become an indispensable tool in people's lives and work. As a programmer, implementing a calculator is an essential skill. In this article, we will explore how to implement a simple calculator using Golang.
First, we need to define the basic functions of the calculator, including addition, subtraction, multiplication, division and remainder. The code is as follows:
package?main import?"fmt" func?main()?{ ????var?operator?string ????var?num1,?num2?float64 ????fmt.Print("請(qǐng)輸入操作符(+、-、*、/、%):") ????fmt.Scanln(&operator) ????fmt.Print("請(qǐng)輸入第一個(gè)數(shù)字:") ????fmt.Scanln(&num1) ????fmt.Print("請(qǐng)輸入第二個(gè)數(shù)字:") ????fmt.Scanln(&num2) ????result?:=?0.0 ????switch?operator?{ ????case?"+": ????????result?=?num1?+?num2 ????case?"-": ????????result?=?num1?-?num2 ????case?"*": ????????result?=?num1?*?num2 ????case?"/": ????????result?=?num1?/?num2 ????case?"%": ????????result?=?float64(int(num1)?%?int(num2)) ????default: ????????fmt.Println("您輸入的操作符不正確,支持的操作符有:+、-、*、/、%") ????} ????if?operator?!=?""?{ ????????fmt.Printf("%.2f?%s?%.2f?=?%.2f",?num1,?operator,?num2,?result) ????} }
In this code, we use the fmt
package to get the operators and numbers entered by the user. Then use the switch
statement to implement calculations of different operators, and finally output the calculation results. It should be noted that in order to handle the remainder operator, we need to cast the number to an integer for calculation, and then convert the result to a floating point type.
If you want your calculator to support multiple calculations, you can encapsulate the above code into an infinite loop program, as shown below:
package?main import?"fmt" func?main()?{ ????for?{ ????????var?operator?string ????????var?num1,?num2?float64 ????????fmt.Print("請(qǐng)輸入操作符(+、-、*、/、%),退出請(qǐng)輸入quit:") ????????fmt.Scanln(&operator) ????????if?operator?==?"quit"?{ ????????????break ????????} ????????fmt.Print("請(qǐng)輸入第一個(gè)數(shù)字:") ????????fmt.Scanln(&num1) ????????fmt.Print("請(qǐng)輸入第二個(gè)數(shù)字:") ????????fmt.Scanln(&num2) ????????result?:=?0.0 ????????switch?operator?{ ????????case?"+": ????????????result?=?num1?+?num2 ????????case?"-": ????????????result?=?num1?-?num2 ????????case?"*": ????????????result?=?num1?*?num2 ????????case?"/": ????????????result?=?num1?/?num2 ????????case?"%": ????????????result?=?float64(int(num1)?%?int(num2)) ????????default: ????????????fmt.Println("您輸入的操作符不正確,支持的操作符有:+、-、*、/、%") ????????} ????????if?operator?!=?""?{ ????????????fmt.Printf("%.2f?%s?%.2f?=?%.2f\n",?num1,?operator,?num2,?result) ????????} ????} }
This program will continue to execute until the user Type quit
to exit.
Summary
It is not difficult to write a calculator using Golang, you only need to master some basic syntax and logic. In this article, we discuss how to use Golang to implement simple addition, subtraction, multiplication, division, and remainder operations and package them into reusable programs. I hope this article can be helpful to you and allow you to better understand and use Golang.
The above is the detailed content of How to implement a calculator using golang. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

To create a buffer channel in Go, just specify the capacity parameters in the make function. The buffer channel allows the sending operation to temporarily store data when there is no receiver, as long as the specified capacity is not exceeded. For example, ch:=make(chanint,10) creates a buffer channel that can store up to 10 integer values; unlike unbuffered channels, data will not be blocked immediately when sending, but the data will be temporarily stored in the buffer until it is taken away by the receiver; when using it, please note: 1. The capacity setting should be reasonable to avoid memory waste or frequent blocking; 2. The buffer needs to prevent memory problems from being accumulated indefinitely in the buffer; 3. The signal can be passed by the chanstruct{} type to save resources; common scenarios include controlling the number of concurrency, producer-consumer models and differentiation

In Go language, calling a structure method requires first defining the structure and the method that binds the receiver, and accessing it using a point number. After defining the structure Rectangle, the method can be declared through the value receiver or the pointer receiver; 1. Use the value receiver such as func(rRectangle)Area()int and directly call it through rect.Area(); 2. If you need to modify the structure, use the pointer receiver such as func(r*Rectangle)SetWidth(...), and Go will automatically handle the conversion of pointers and values; 3. When embedding the structure, the method of embedded structure will be improved, and it can be called directly through the outer structure; 4. Go does not need to force use getter/setter,

In Go, an interface is a type that defines behavior without specifying implementation. An interface consists of method signatures, and any type that implements these methods automatically satisfy the interface. For example, if you define a Speaker interface that contains the Speak() method, all types that implement the method can be considered Speaker. Interfaces are suitable for writing common functions, abstract implementation details, and using mock objects in testing. Defining an interface uses the interface keyword and lists method signatures, without explicitly declaring the type to implement the interface. Common use cases include logs, formatting, abstractions of different databases or services, and notification systems. For example, both Dog and Robot types can implement Speak methods and pass them to the same Anno

TointegrateGolangserviceswithexistingPythoninfrastructure,useRESTAPIsorgRPCforinter-servicecommunication,allowingGoandPythonappstointeractseamlesslythroughstandardizedprotocols.1.UseRESTAPIs(viaframeworkslikeGininGoandFlaskinPython)orgRPC(withProtoco

In Go language, string operations are mainly implemented through strings package and built-in functions. 1.strings.Contains() is used to determine whether a string contains a substring and returns a Boolean value; 2.strings.Index() can find the location where the substring appears for the first time, and if it does not exist, it returns -1; 3.strings.ReplaceAll() can replace all matching substrings, and can also control the number of replacements through strings.Replace(); 4.len() function is used to obtain the length of the bytes of the string, but when processing Unicode, you need to pay attention to the difference between characters and bytes. These functions are often used in scenarios such as data filtering, text parsing, and string processing.

TheGoiopackageprovidesinterfaceslikeReaderandWritertohandleI/Ooperationsuniformlyacrosssources.1.io.Reader'sReadmethodenablesreadingfromvarioussourcessuchasfilesorHTTPresponses.2.io.Writer'sWritemethodfacilitateswritingtodestinationslikestandardoutpu

Go's time package provides functions for processing time and duration, including obtaining the current time, formatting date, calculating time difference, processing time zone, scheduling and sleeping operations. To get the current time, use time.Now() to get the Time structure, and you can extract specific time information through Year(), Month(), Day() and other methods; use Format("2006-01-0215:04:05") to format the time string; when calculating the time difference, use Sub() or Since() to obtain the Duration object, and then convert it into the corresponding unit through Seconds(), Minutes(), and Hours();

InGo,ifstatementsexecutecodebasedonconditions.1.Basicstructurerunsablockifaconditionistrue,e.g.,ifx>10{...}.2.Elseclausehandlesfalseconditions,e.g.,else{...}.3.Elseifchainsmultipleconditions,e.g.,elseifx==10{...}.4.Variableinitializationinsideif,l
