Go 语言程序可以创建一个类来执行基本的计算器操作
要创建可以执行基本计算器操作的类,我们可以采取以下步骤:
- 我们使用两个数字a和b来定义一个计算器类。
- 定义成员方法来计算两个数字的加法。
- 定义成员方法来计算两个数字的乘法。
- 定义成员方法来计算两个数字的除法。
- 定义成员方法来计算两个数字的减法。
- 在main方法中声明两个变量,a和b。
- 获取计算器实例。
- 初始化一个选择变量,根据该变量可以执行哪种数学运算。
示例
package main import ( "fmt" ) type Calculator struct { a int b int } func (c *Calculator)Add(){ fmt.Println("Addition of two numbers: ", c.a + c.b) } func (c *Calculator)Mul(){ fmt.Println("Multiplication of two numbers: ", c.a * c.b) } func (c *Calculator)Div(){ fmt.Println("Division of two numbers: ", c.a / c.b) } func (c *Calculator)Sub(){ fmt.Println("Subtraction of two numbers: ", c.a - c.b) } func main(){ var a, b int fmt.Print("Enter the first number: ") fmt.Scanf("%d", &a) fmt.Print("Enter the second number: ") fmt.Scanf("%d", &b) cal := Calculator{ a: a, b: b, } c:=1 for c>=1 { fmt.Println("Enter 1 for Addition: ") fmt.Println("Enter 2 for Multiplication: ") fmt.Println("Enter 3 for Division: ") fmt.Println("Enter 4 for Subtraction: ") fmt.Print("Enter 5 for Exit: ") fmt.Scanf("%d", &c) switch c { case 1: cal.Add() case 2: cal.Mul() case 3: cal.Div() case 4: cal.Sub() case 5: c = 0 break default: fmt.Println("Enter valid number.") } } }
输出
Enter the first number: 7 Enter the second number: 3 Enter 1 for Addition: Enter 2 for Multiplication: Enter 3 for Division: Enter 4 for Subtraction: Enter 5 for Exit: 1 Addition of two numbers: 10 Enter 1 for Addition: Enter 2 for Multiplication: Enter 3 for Division: Enter 4 for Subtraction: Enter 5 for Exit: 2 Multiplication of two numbers: 21 Enter 1 for Addition: Enter 2 for Multiplication: Enter 3 for Division: Enter 4 for Subtraction: Enter 5 for Exit: 3 Division of two numbers: 2 Enter 1 for Addition: Enter 2 for Multiplication: Enter 3 for Division: Enter 4 for Subtraction: Enter 5 for Exit: 4 Subtraction of two numbers: 4 Enter 1 for Addition: Enter 2 for Multiplication: Enter 3 for Division: Enter 4 for Subtraction: Enter 5 for Exit: 5
广告