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
廣告